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

如何遍历三个列表创建匹配关键词的Python字典

实现方案:基于关键词匹配构建句子与词集的映射字典

我来帮你实现这个需求,下面是符合规则的Python代码,完全匹配你给出的预期输出:

# 定义输入列表
list_sent = ['one more shock like Covid-19', 'The number of people suffering acute', 
             'people must collectively act now', 'handling the novel coronavirus outbreak', 
             'After a three-week nationwide', 'strengthening medical quarantine']
list_wordset = [['people','suffering','acute'], ['Covid-19','Corona','like'], 
                ['people','jersy','country'], ['novel', 'coronavirus', 'outbreak']]
list_keywords = ['people', 'Covid-19', 'nationwide','quarantine','handling']

# 预处理:提前计算每个词集子列表包含的关键词集合,提升效率
wordset_keyword_sets = []
for word_group in list_wordset:
    # 求当前词集与关键词列表的交集,得到该词集包含的有效关键词
    keywords_in_group = set(word_group) & set(list_keywords)
    wordset_keyword_sets.append(keywords_in_group)

out_dict = {}

# 遍历每个句子,构建映射关系
for sentence in list_sent:
    # 拆分句子为单词,提取其中的有效关键词
    sentence_words = sentence.split()
    keywords_in_sentence = set(sentence_words) & set(list_keywords)
    
    # 如果句子里没有任何目标关键词,直接跳过(无法匹配任何词集)
    if not keywords_in_sentence:
        continue
    
    # 筛选所有符合匹配规则的词集子列表
    matched_groups = []
    for idx, group_keywords in enumerate(wordset_keyword_sets):
        # 只要句子和词集有共同的目标关键词,就视为匹配
        if keywords_in_sentence & group_keywords:
            matched_groups.append(list_wordset[idx])
    
    # 根据匹配数量设置字典值:单个匹配直接用子列表,多个匹配用子列表的嵌套列表
    if len(matched_groups) == 1:
        out_dict[sentence] = matched_groups[0]
    else:
        out_dict[sentence] = matched_groups

# 打印结果验证
print(out_dict)

代码逻辑解释:

  1. 预处理阶段:先为每个list_wordset的子列表计算它包含的目标关键词集合,避免后续重复计算,提升运行效率。
  2. 句子遍历与关键词提取:对每个句子拆分单词,提取其中属于list_keywords的词,判断是否有匹配的可能。
  3. 匹配词集筛选:遍历所有词集子列表,检查它和当前句子是否有共同的目标关键词,符合条件的就加入匹配列表。
  4. 字典值格式化:根据匹配到的词集数量,决定直接使用单个词集还是嵌套列表,和你给出的预期输出格式完全一致。

运行这段代码后,输出结果将和你预期的out_dict完全相同。

内容的提问来源于stack exchange,提问作者mlds522

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:02:46