从字符串中去除标点符号的最佳方法 [英] Best way to strip punctuation from a string
问题描述
似乎应该有比以下更简单的方法:
It seems like there should be a simpler way than:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有吗?
推荐答案
从效率的角度来看,你不会被打败
From an efficiency perspective, you're not going to beat
s.translate(None, string.punctuation)
对于更高版本的 Python,请使用以下代码:
For higher versions of Python use the following code:
s.translate(str.maketrans('', '', string.punctuation))
它使用查找表在 C 中执行原始字符串操作 - 除了编写您自己的 C 代码之外,没有什么比这更好的了.
It's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code.
如果不担心速度,另一种选择是:
If speed isn't a worry, another option though is:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
这比使用每个字符的 s.replace 快,但性能不如非纯 python 方法,例如正则表达式或 string.translate,正如您从下面的时序中看到的那样.对于这种类型的问题,在尽可能低的水平上做是有回报的.
This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.
时间代码:
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
这篇关于从字符串中去除标点符号的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!