从字符串中删除标点符号的最佳方法
当尝试从 Python 中的字符串中删除标点符号时,可以使用以下方法:
import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation)
但是,这种方法可能显得过于复杂。有没有更简单的解决方案?
效率角度
为了达到最佳效率,很难超越:
s.translate(None, string.punctuation)
这段代码利用了C的原始字符串使用查找表进行操作,提供高度优化的
替代方法
如果速度不是主要问题,请考虑以下替代方法:
exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude)
此选项比使用更快s.replace 每个字符,但仍然优于非纯 Python 方法,例如string.translate.
时序分析
为了比较这些方法的性能,使用以下时序代码:
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): return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): 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)
结果表明:
因此,为了高效标点符号去除,它是建议使用 s.translate(None, string.punctuation) (对于较低的 Python 版本)或s.translate(str.maketrans('', '', string.punctuation)) (对于更高的 Python 版本)代码。
以上是在 Python 中从字符串中删除标点符号的最有效方法是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!