我过去常常跑步
$s =~ s/[^[:print:]]//g;
在Perl上删除不可打印的字符。
在Python中没有POSIX正则表达式类,我不能写:print:让它意味着我想要的东西。我不知道在Python中有没有办法检测字符是否可打印。
你怎么做?
编辑:它还必须支持Unicode字符。string.printable方法将很高兴地将它们从输出中剥离出来。对于任何unicode字符,curses.ascii.isprint都将返回false。
发布于 2008-09-18 13:23:15
据我所知,最有效的方法是:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
发布于 2008-09-18 15:25:38
您可以尝试使用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)
有关可用类别的信息,请参见第175页的Unicode database character properties中的表4-9
发布于 2014-09-14 10:20:40
在Python 3中,
def filter_nonprintable(text):
import itertools
# Use characters of control category
nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))
# Use translate to remove all non-printable characters
return text.translate({character:None for character in nonprintable})
有关.translate()与正则表达式& .replace()的比较,请参阅this StackOverflow post on removing punctuation
这些范围可以使用@Ants Aasma所示的Unicode character database categories通过nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc')
生成。
https://stackoverflow.com/questions/92438
复制相似问题