猿问

从python中的字符串中剥离不可打印的字符

从python中的字符串中剥离不可打印的字符

我用来跑

$s =~ s/[^[:print:]]//g;

在Perl上摆脱不可打印的字符。

在Python中没有POSIX正则表达式类,我不能写[:print:]让它意味着我想要的东西。我知道在Python中无法检测字符是否可打印。

你会怎么做?

编辑:它也必须支持Unicode字符。string.printable方式很乐意将它们从输出中剥离出来。对于任何unicode字符,curses.ascii.isprint都将返回false。


陪伴而非守候
浏览 848回答 3
3回答

幕布斯7119047

遗憾的是,迭代字符串在Python中相当慢。对于这种事情,正则表达式要快一个数量级。你只需要自己构建角色类。该unicodedata模块是这个相当有帮助,尤其是unicodedata.category()函数。有关类别的说明,请参阅Unicode字符数据库。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 efficientlycontrol_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)

桃花长相依

您可以尝试使用以下unicodedata.category()功能设置过滤器:import unicodedata printable = {'Lu', 'Ll'}def filter_non_printable(str):   return ''.join(c for c in str if unicodedata.category(c) in printable)有关可用类别的Unicode数据库字符属性,请参见第175页的表4-9
随时随地看视频慕课网APP

相关分类

Python
我要回答