如果您正在使用python2并且您的输入是字符串(不是unicodes),那么绝对最好的方法是remove_chars_translate_bytes:
>>> chars_to_remove = ['.', '!', '?']
>>> subj = 'A.B!C?'
>>> subj.translate(None, ''.join(chars_to_remove))
'ABC'
否则,有以下选项可供考虑:
A.通过char迭代主题char,省略不需要的字符和结果列表remove_chars_translate_bytes:
>>> sc = set(chars_to_remove)
>>> ''.join([c for c in subj if c not in sc])
'ABC'
(请注意,生成器版本remove_chars_translate_bytes效率较低)。
B.动态创建正则表达式,并使用空字符串创建remove_chars_translate_bytes:
>>> import re
>>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
>>> re.sub(rx, '', subj)
'ABC'
(remove_chars_translate_bytes确保像remove_chars_translate_bytes或]这样的字符不会破坏正则表达式)。
C.使用remove_chars_translate_bytes的映射变体:
>>> chars_to_remove = [u'δ', u'Γ', u'ж']
>>> subj = u'AжBδCΓ'
>>> dd = {ord(c):None for c in chars_to_remove}
>>> subj.translate(dd)
u'ABC'
完整的测试代码和时间:
#coding=utf8
import re
def remove_chars_iter(subj, chars):
sc = set(chars)
return ''.join([c for c in subj if c not in sc])
def remove_chars_re(subj, chars):
return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)
def remove_chars_re_unicode(subj, chars):
return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)
def remove_chars_translate_bytes(subj, chars):
return subj.translate(None, ''.join(chars))
def remove_chars_translate_unicode(subj, chars):
d = {ord(c):None for c in chars}
return subj.translate(d)
import timeit, sys
def profile(f):
assert f(subj, chars_to_remove) == test
t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
print ('{0:.3f} {1}'.format(t, f.__name__))
print (sys.version)
PYTHON2 = sys.version_info[0] == 2
print ('\n"plain" string:\n')
chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?' * 1000
test = 'ABC' * 1000
profile(remove_chars_iter)
profile(remove_chars_re)
if PYTHON2:
profile(remove_chars_translate_bytes)
else:
profile(remove_chars_translate_unicode)
print ('\nunicode string:\n')
if PYTHON2:
chars_to_remove = [u'δ', u'Γ', u'ж']
subj = u'AжBδCΓ'
else:
chars_to_remove = ['δ', 'Γ', 'ж']
subj = 'AжBδCΓ'
subj = subj * 1000
test = 'ABC' * 1000
profile(remove_chars_iter)
if PYTHON2:
profile(remove_chars_re_unicode)
else:
profile(remove_chars_re)
profile(remove_chars_translate_unicode)
结果:
2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
"plain" string:
0.637 remove_chars_iter
0.649 remove_chars_re
0.010 remove_chars_translate_bytes
unicode string:
0.866 remove_chars_iter
0.680 remove_chars_re_unicode
1.373 remove_chars_translate_unicode
---
3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
"plain" string:
0.512 remove_chars_iter
0.574 remove_chars_re
0.765 remove_chars_translate_unicode
unicode string:
0.817 remove_chars_iter
0.686 remove_chars_re
0.876 remove_chars_translate_unicode
(作为旁注,remove_chars_translate_bytes的数字可能会给我们一个线索,为什么业界不愿意长期采用Unicode)。