根据多个列表中出现的单词进行关键字检查

时间:2018-07-17 09:02:11

标签: regex string python-3.x dictionary pattern-matching

我有类似的字典:

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,看看是否每个字符串都包含cf_dict中任何列表(cf_dict的值是列表)中的关键字any,如果存在,则返回该字符串(文档中的字符串)的相应key(基于值)作为输出。

例如,如果我检查列表docs,则输出将为[fruitscountries]

与此answer类似,但是它只检查一个列表,但是,我想检查多个列表。

1 个答案:

答案 0 :(得分:2)

如果字符串与多个列表中的值匹配(例如'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'}}