首页  >  文章  >  后端开发  >  如何从 Python 字符串中删除不可打印的字符?

如何从 Python 字符串中删除不可打印的字符?

Susan Sarandon
Susan Sarandon原创
2024-10-22 06:58:30300浏览

How to Remove Non-Printable Characters from Python Strings?

从 Python 中的字符串中删除不可打印的字符

问题:

在 Perl 中,可以使用正则表达式 s/[^[:print:]]//g 删除不可打印的字符。但是,在 Python 中,不支持 [:print:] 类。我们如何在Python中实现类似的同时处理ASCII和Unicode字符的功能?

答案:

由于Python在检测可打印性方面的限制,我们可以构造自己的字符使用 unicodedata 模块的类。

<code class="python">import unicodedata, re, itertools, sys

# Generate a list of all characters
all_chars = (chr(i) for i in range(sys.maxunicode))

# Category of control characters
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)

# Escape the control characters for regular expression matching
control_char_re = re.compile('[%s]' % re.escape(control_chars))

# Function to remove control characters from a string
def remove_control_chars(s):
    return control_char_re.sub('', s)</code>

对于 Python 2:

<code class="python">import unicodedata, re, sys

# Generate a list of all characters
all_chars = (unichr(i) for i in xrange(sys.maxunicode))

# Category of control characters
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)

# Escape the control characters for regular expression matching
control_char_re = re.compile('[%s]' % re.escape(control_chars))

# Function to remove control characters from a string
def remove_control_chars(s):
    return control_char_re.sub('', s)</code>

扩展选项:

对于更全面的删除,可以包含其他类别,尽管这可能会影响性能。

字符类别和计数:

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

以上是如何从 Python 字符串中删除不可打印的字符?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn