如何使用字典标准化多来源解析后二维列表中的术语?
术语标准化问题的解决方法
我在解析多份PDF时遇到术语表述不统一的问题,比如不同来源将Batman写成The Batman、bat man等。为此我创建了用于统一术语的字典:
Voc_dict = {'Batman':'Batman', 'the Batman': 'Batman', 'bat man': 'Batman'}
现在需要标准化以下二维列表中的文本内容:
Super_list = [['among the heros with daddy issues, the bat man shines'], ['Bat man protects the city with everything he gots']]
我尝试通过遍历列表和字典实现,但代码没有生效:
For i in super_list: For key, value in voc_dict.items(): i.replace(voc_dict[key], voc_dict[value])
问题根源
- Python循环关键字是小写
for,大写For会直接触发语法错误。 Super_list是二维列表,每个元素是包含单个字符串的子列表,直接对列表调用replace方法无效,必须先获取子列表内的字符串。- 字符串是不可变类型,
replace方法不会修改原字符串,需要将返回的新字符串重新赋值回原位置。 - 未考虑替换顺序:如果先替换短术语,可能会破坏长术语的匹配(比如先替换
Batman后,the Batman可能只剩the无法匹配),因此需要优先替换更长的术语。
正确实现代码
# 按术语长度从长到短排序,优先匹配长术语 sorted_voc = sorted(Voc_dict.items(), key=lambda x: len(x[0]), reverse=True) # 遍历二维列表的每个子列表 for sub_list in Super_list: # 遍历子列表中的每个文本(此处每个子列表仅含一个字符串) for idx, text in enumerate(sub_list): # 依次替换每个术语 for key, standard_term in sorted_voc: # 若需要不区分大小写匹配,用下面这行 text = text.replace(key.lower(), standard_term) # 若只需要精准匹配,替换为:text = text.replace(key, standard_term) # 将替换后的文本存回原列表位置 sub_list[idx] = text # 查看处理后的结果 print(Super_list)
运行结果
[['among the heros with daddy issues, Batman shines'], ['Batman protects the city with everything he gots']]
内容的提问来源于stack exchange,提问作者H. H.
相关产品推荐
相关产品推荐

