首页 > 解决方案 > 基于多个列表中存在的单词的关键字检查

问题描述

我有一本类似的字典:

countries = ["usa", "france", "japan", "china", "germany"]
fruits = ["mango", "apple", "passion-fruit", "durion", "bananna"]

cf_dict = {k:v for k,v in zip(["countries", "fruits"], [countries, fruits])}

我也有一个类似的字符串列表:

docs = ["mango is a fruit that is very different from Apple","I like to travel, last year I was in Germany but I like France.it was lovely"]

我想检查docs并查看每个字符串是否包含anycf_dict 中任何列表(cf_dict 的值是列表)中的关键字,如果它们存在则返回该字符串的对应key(基于值)(字符串在文档中)作为输出。

例如,如果我检查列表docs,输出将是 [ fruits, countries]

类似于此答案的内容,但这仅检查一个列表,但是,我想检查多个列表。

标签: regexstringpython-3.xdictionarypattern-matching

解决方案


如果字符串与多个列表中的值匹配(例如'apple grows in USA'应该映射到{'fruits', 'countries'}),则以下返回集合的字典。

print({s: {k for k, l in cf_dict.items() for w in l if w in s.lower()} for s in docs})

这输出:

{'mango is a fruit that is very different from Apple': {'fruits'}, 'I like to travel, last year I was in Germany but I like France.it was lovely': {'countries'}}

推荐阅读