检测unicode字符串中的非ascii字符

Suk*_*tto 3 python unicode python-3.x

给定一个文本文件(或unicode字符串),检测不在ascii编码之外的字符的好方法是什么?我可以很容易地迭代传递每个角色ord(),但我想知道是否有更高效,优雅或惯用的方式来做到这一点.

这里的最终目标是编译无法编码为ascii的数据中的字符列表.

如果重要,我的语料库大小约为500MB/1200文本文件.在Win7(64位)上运行(预编译的vanilla)Python 3.3.1.

Aya*_*Aya 9

这里的最终目标是编译无法编码为ascii的数据中的字符列表.

我能想到的最有效的方法是使用re.sub()去除任何有效的ASCII字符,这将留下包含所有非ASCII字符的字符串.

这只会删除可打印的字符......

>>> import re
>>> print re.sub('[ -~]', '', u'£100 is worth more than €100')
£€
Run Code Online (Sandbox Code Playgroud)

...或者如果你想包含不可打印的字符,请使用此...

>>> print re.sub('[\x00-\x7f]', '', u'£100 is worth more than €100')
£€
Run Code Online (Sandbox Code Playgroud)

要消除欺骗,只需创建一个set()返回的字符串...

>>> print set(re.sub('[\x00-\x7f]', '', u'£€£€'))
set([u'\xa3', u'\u20ac'])
Run Code Online (Sandbox Code Playgroud)