擅长:python、mysql、java
<p>不幸的是,在Python中,遍历字符串的速度相当慢。对于这种情况,正则表达式的速度要快一个数量级以上。你只需要自己建立角色类。unicodedata</em>模块对此非常有帮助,特别是<em>unicodedata.category()</em>函数。有关类别的说明,请参见<a href="http://www.unicode.org/reports/tr44/#General_Category_Values" rel="noreferrer">Unicode Character Database</a>。</p>
<pre><code>import unicodedata, re
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0,32) + range(127,160)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
</code></pre>