我用来运行
$s =~ s/[^[:print:]]//g;
在 Perl 上摆脱不可打印的字符。
在 Python 中没有 POSIX 正则表达式类,我不能写 [:print:] 让它意味着我想要的。我知道在 Python 中无法检测字符是否可打印。
你会怎么做?
编辑:它还必须支持 Unicode 字符。 string.printable 方式会很高兴地将它们从输出中剥离出来。 curses.ascii.isprint 将为任何 unicode 字符返回 false。
最佳答案
不幸的是,在 Python 中迭代字符串相当慢。对于这种事情,正则表达式的速度要快一个数量级。您只需要自己构建角色类。 unicodedata 模块对此非常有帮助,尤其是 unicodedata.category() 函数。见 Unicode Character Database有关类别的说明。
import unicodedata, re, itertools, sys
all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
对于 Python2
import unicodedata, re, sys
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
对于某些用例,附加类别(例如,所有来自 control 组的类别可能更可取,尽管这可能会减慢处理时间并显着增加内存使用量。每个类别的字符数:
抄送
(控制):65Cf
(格式):161Cs
(代理):2048Co
(私有(private)使用):137468Cn
(未分配):836601
编辑从评论中添加建议。
关于python - 从python中的字符串中去除不可打印的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/92438/