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

2024-05-13 08:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我经常跑步

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

在Perl上去掉不可打印的字符。

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

你会怎么做?

编辑:它还必须支持Unicode字符。string.printable方式会很高兴地将它们从输出中剥离出来。 curses.ascii.isprint将为任何unicode字符返回false。


Tags: 编辑string方式asciiunicode代表字符跑步
3条回答

您可以尝试使用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 database character properties中第175页的表4-9

不幸的是,在Python中,遍历字符串的速度相当慢。对于这种情况,正则表达式的速度要快一个数量级以上。你只需要自己建立角色类。unicodedata模块对此非常有帮助,特别是unicodedata.category()函数。有关类别的说明,请参见Unicode Character Database

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)

据我所知,最有效的方法是:

import string

filtered_string = filter(lambda x: x in string.printable, myStr)

相关问题 更多 >