似乎应该有一个比以下方法更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有没有?
从效率的角度来看,您不会被击败
s.translate(None, string.punctuation)
对于更高版本的 Python,请使用以下代码:
s.translate(str.maketrans('', '', string.punctuation))
它使用查找表在 C 中执行原始字符串操作 - 除了编写自己的 C 代码之外,没有什么比这更好的了。
如果不必担心速度,那么还有另一种选择:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
从每个字符来看,这比 s.replace 更快,但是却不能像正则表达式或 string.translate 这样的非纯 python 方法那样好用,正如您从以下时序中所见。对于这种类型的问题,以尽可能低的水平进行操作会有所回报。
时间码:
import re, string, timeit
s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))
def test_set(s):
return ''.join(ch for ch in s if ch not in exclude)
def test_re(s): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):
return s.translate(table, string.punctuation)
def test_repl(s): # From S.Lott's solution
for c in string.punctuation:
s=s.replace(c,"")
return s
print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)
得到以下结果:
sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802
如果您知道正则表达式,就足够简单了。
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
为了方便使用,我在 Python 2 和 Python 3 中总结了从字符串中删除标点符号的注意事项。有关详细说明,请参阅其他答案。
的 Python 2
import string
s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation) # Output: string without punctuation
的 Python 3
import string
s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation}
new_s = s.translate(table) # Output: string without punctuation