python - 从 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' ]
我应该如何更正它的代码以匹配文件内容的行?
解决方案
问题是您从文件中读取的行实际上包含 12 个字符:\
, x
, e
, d
, \
, x
, b
, a
, \
, x
,b
和d
,并且您想将其转换为 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']
推荐阅读
- postgresql - 无法使用 pgAdmin 连接到服务器 PostgreSQL 数据库
- angular - 字段退出后和字段中的角度表单字段验证
- raspberry-pi - 当类作为 Raspberry Pi 上的 python 对象传递时找不到相机
- javascript - 如何在为生产运行 npm build 时解决多个块向相同文件名错误(bundle.css)发出资产 [Vue.js]
- python - 在长达一个月的列中概括确认的金额
- azure - 在创建应用程序网关入口时,问题正在发生
- java - 如何使用 Mockito 验证 PreparedStatement 场景。无法在测试类中模拟 PreparedStatement 类
- python - Django:ForeignKey vs related_name
- javascript - 图表!日期顺序值从高到低
- freeradius - Freeradius 3没有将会计记录保存到Mysql