【问题标题】:keyword inspection based on words present in multiple lists基于多个列表中存在的单词的关键字检查
【发布时间】:2018-12-24 21:53:23
【问题描述】:

我有一本类似的字典:

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,如果它们存在则返回相应的@该字符串(文档中的字符串)的 987654326@(基于值)作为输出。

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

类似于answer 的东西,但它只检查一个列表,但是,我想检查多个列表。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2017-02-28
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 2021-06-11
      • 2020-09-11
      相关资源
      最近更新 更多