python - 从python中的字符串中去除不可打印的字符

标签 python string non-printable

我用来运行

$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 组的类别可能更可取,尽管这可能会减慢处理时间并显着增加内存使用量。每个类别的字符数:

  • 抄送(控制):65
  • Cf(格式):161
  • Cs(代理):2048
  • Co(私有(private)使用):137468
  • Cn(未分配):836601

编辑从评论中添加建议。

关于python - 从python中的字符串中去除不可打印的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/92438/

相关文章:

python - 如何更改 pygame 窗口顶部栏的颜色?

python - 带箭头的 matplotlib 3d 线图无法接受 kwargs

python - 导入 Tensorflow 时 Jupyter Notebook 内核死机

Python PdfMiner - 如何获取 pdf 中包含的每个单词/句子的方向信息?

regex - 为什么 POSIX "printable characters"类不匹配简单字符串?

perl - 在 Win32 Perl 中使用 XML::Twig 字符串损坏和不可打印字符

Python:使用 Lambda 将字符串字段拆分为 3 个单独的字段

c++ - 在代码中包含 100 多个单词的最佳方法是什么?

python - 比较字符串中的各个字符并接受输入为真,即使拼写不准确

c - 输入带有不可打印字符的字符串