我有一些带有unicode编码行的文件,比如D\u00f3nde est\u00e1s
。
我想检查每个单词是否只包含设置区域设置中的字符。你知道吗
这个代码不能完全工作。字符串似乎正确地转换为Dónde estás
,wordmatch匹配每个单词,但它不考虑区域设置。例如,如果我将locale设置为en\u US,它仍然匹配这两个单词,即使它们包含ó
和á
字符。你知道吗
使用关于区域设置而不是关于UNICODE也似乎不起作用,两个单词不再匹配wordmatch正则表达式。你知道吗
import re
import locale
locale.setlocale(locale.LC_ALL,'en_ES')
wordmatch=re.compile(r'^\w*$',re.UNICODE)
line="D\u00f3nde est\u00e1s"
line=line.decode('unicode_escape')
for word in line.split():
if wordmatch.match(word):
print "Matched "+word
else:
print "No match "+word
更改区域设置并不直接意味着更改编码,
en_US
的编码不是强制的ascii
。例如,在我的系统上,它是iso-8859-1
,一种编码,其中ó
和á
是有效的。这可以解释为什么re.LOCALE
不抱怨这些字符。你知道吗要操作编码,我宁愿使用
encode
函数而不是正则表达式:相关问题 更多 >
编程相关推荐