首页 > 解决方案 > 从 python 中的文件中读取错误 UTF 数据列表并将其与一行进行比较

问题描述

让我有这个字符序列

>>> '\xed\xba\xbd'
'íº½'

Myconf_file包含这些字符串的列表,如果它们出现在一行中并且必须被排除,则必须对其进行比较。

$cat excl_char_seq.lst
\xed\xba\xbd
\xed\xa9\x81
\xed\xba\x91

这是我的代码来比较一行是否包含这些序列中的任何一个。

v_conf_file = 'excl_char_seq.lst'   
with open(v_conf_file) as f:
     seqlist = f.read().splitlines()
line = 'weríº½66'
print ([ 1 for seqs in seqlist if seqs in line ])

但是上面代码的打印列表是的。

当我打印 seqlist 时,我得到了以下输出,它似乎用“\”转义了序列。

['\\xed\\xba\\xbd', '\\xed\\xa9\\x81', '\\xed\\xba\\x91' ]

我应该如何更正它的代码以匹配文件内容的行?

标签: pythonpython-2.6

解决方案


问题是您从文件中读取的行实际上包含 12 个字符:\, x, e, d, \, x, b, a, \, x,bd,并且您想将其转换为 3 个字符'\xed''\xba'和 ' \xbd'。正则表达式可以帮助识别以开头的转义\x字符:

def unescape(string):
    rx = re.compile(r'(\\x((?:[0-9a-fA-F]){2}))')
    while True:
        m = rx.search(string)
        if m is None: return string
        string = string.replace(m.group(1), chr(int(m.group(2), 16)))

您可以使用它来预处理从文件中提取的行(不要忘记导入re模块):

v_conf_file = 'excl_char_seq.lst'   
with open(v_conf_file) as f:
     seqlist = [ unescape(line.strip()) for line in fd ]
line = 'weríº½66'
print ([ 1 for seqs in seqlist if seqs in line ])

当我控制 的内容时seqlist,我得到了预期:

>>> print seqlist
['\xed\xba\xbd', '\xed\xa9\x81', '\xed\xba\x91']

推荐阅读