正则表达式的Python unicode编码

2024-09-30 14:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些带有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

Tags: importre区域lineunicode字符单词locale
1条回答
网友
1楼 · 发布于 2024-09-30 14:29:32

更改区域设置并不直接意味着更改编码,en_US的编码不是强制的ascii。例如,在我的系统上,它是iso-8859-1,一种编码,其中óá是有效的。这可以解释为什么re.LOCALE不抱怨这些字符。你知道吗

要操作编码,我宁愿使用encode函数而不是正则表达式:

line="D\u00f3nde est\u00e1s"
line=line.decode('unicode_escape')

# get current encoding, or set to "ascii" if you want to be more restrictive
pref_encoding = locale.getpreferedencoding()

for word in line.split():
    try:
        w = word.encode(pref_encoding)
    except UnicodeEncodeError as e:
        print "This word contains unacceptable characters: ", word
        break

相关问题 更多 >