从 python 中的文件中读取错误的 UTF 数据列表,并将其与一行进行比较

Read a list of bad UTF data from a file in python and compare it with a line

让我有这个字符序列

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

我的 conf_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' ]

我应该如何更正代码以使其与文件内容匹配?

问题是您从文件中读取的行实际上包含 12 个字符:\xed\xba\xbd,并且您想将其转换到 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']