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

我使用运行

我使用运行

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

在 Perl 上删除不可打印的字符。

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

你会怎么做?

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

92

不幸的是,在 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组的类别可能更可取,尽管这可能会减慢处理时间并显着增加内存使用量。

Cc(控制):65

Cf(格式):161

Cs(代理):2048

Co(私人使用):137468

Cn(未分配):836601

编辑从评论中添加建议。

84

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

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

您可以尝试使用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

14

以下将使用 Unicode 输入,并且相当快...

import sys
# build a table mapping all non-printable characters to None
NOPRINT_TRANS_TABLE = {
    i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()
}
def make_printable(s):
    """Replace non-printable characters in a string."""
    # the translate method on str removes characters
    # that map to None from the string
    return s.translate(NOPRINT_TRANS_TABLE)
ert make_printable('Café') == 'Café'
ert make_printable('\x00\x11Hello') == 'Hello'
ert make_printable('') == ''

我自己的测试表明,这种方法比遍历字符串并使用str.join返回结果的函数更快。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(377)
excel在计算单元格的数量时指向单元格
上一篇
如何在 C#中计算XIRR公式
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(75条)