You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字典标准化多来源解析后二维列表中的术语?

术语标准化问题的解决方法

我在解析多份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])

问题根源

  1. Python循环关键字是小写for,大写For会直接触发语法错误。
  2. Super_list是二维列表,每个元素是包含单个字符串的子列表,直接对列表调用replace方法无效,必须先获取子列表内的字符串。
  3. 字符串是不可变类型,replace方法不会修改原字符串,需要将返回的新字符串重新赋值回原位置。
  4. 未考虑替换顺序:如果先替换短术语,可能会破坏长术语的匹配(比如先替换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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:17:17