【问题标题】:How to check if a word or group of words exist in given list of strings and how to extract that word?如何检查给定字符串列表中是否存在一个单词或一组单词以及如何提取该单词?
【发布时间】:2021-02-01 00:55:07
【问题描述】:

我有一个字符串列表如下:

list_of_words = ['all saints church','churchill college', "great saint mary's church", 'holy trinity church', "little saint mary's church", 'emmanuel college']

我有一个字典列表,其中包含“文本”作为键和一个句子作为值。如下:

    "dict_sentences": [
    {
        "text": "Can you help me book a taxi going from emmanuel college to churchill college?"
    },
    {
        "text": "Yes, I could! What time would you like to depart from Emmanuel College?"
    },
    {
        "text": "I want a taxi to holy trinity church"
    },
    {
        "text": "Alright! I have a yellow Lexus booked to pick you up. The Contact number is 07543493643. Anything else I can help with?"
    },
    {
        "text": "No, that is everything I needed. Thank you!"
    },
    {
        "text": "Thank you! Have a great day!"
    }
]

对于 dict_sentences 中的每个句子,我想检查该句子中是否存在 list_of_words 中的任何单词,如果是,我想将其存储在另一个字典中(因为我必须进一步处理它)。

例如,在 dict_sentences 的第一句话中,“你能帮我预订一辆从伊曼纽尔学院到丘吉尔学院的出租车吗?”,子字符串“丘吉尔学院 " 和 'emmanuel College' 存在于我们的 list_of_words 中,所以我想将单词 'churchill College' 和 'emmanuel College' 存储在另一个像{ sent1 : ['churchill college', 'emmanuel college'] }这样的字典

所以预期的输出是:

{  sent1 : ['churchill college', 'emmanuel college'] ,
   sent2 : [ 'emmanuel college' ],
   sent3 : [ 'holy trinity church' ]
} # ignore the rest of sentences as no word from list_of_words exist in them

这里的主要问题是检查给定句子是否包含给定句子中的单词/单词组(如“圣三一教堂” - 3 个单词),如果是,则提取相同的单词。我浏览了其他答案,并建议使用以下代码检查列表中的单词是否出现在句子中:

if any(word in sentence for word in list_of_words()): 
     pass

但是,这样我们只能检查 list_of_words() 中是否存在来自句子的单词,要提取单词,我必须运行 for 循环。但是,我避免使用 for 循环,因为我需要一个非常省时的解决方案,因为我有大约 300 个文档,其中每个文档都包含这样的 10-15(或更多)个句子,并且 list_of_words 也很大,即大约 300 个字符串。因此,我需要一种高效的方法来检查并从 list_of_words 中存在的给定句子中提取单词。

【问题讨论】:

  • 根据你的需要,别以为你别无选择,只能遍历整个列表。您可以尝试首先通过检查是否先出现来缩小文档。

标签: python string list dictionary


【解决方案1】:

您可以使用re.findall,因此没有嵌套循环。

output = {}
find_words = re.compile('|'.join(list_of_words)).findall
for i, (s,) in enumerate(map(dict.values, data['dict_sentences']), 1):
    words = find_words(s.lower())
    if words:
        output[f"sent{i}"] = words

{'sent1': ['emmanuel college', 'churchill college'],
 'sent2': ['emmanuel college'],
 'sent3': ['holy trinity church']}

这可以在 dict_comprehension 中完成,也可以在 python 3.8+ 中使用 walrus 运算符,尽管可能有点过火:

find_sent = re.compile('|'.join(list_of_words)).findall
iter_sent = enumerate(map(dict.values, data['dict_sentences']), 1)
output = {f"sent{i}": words for i, (s,) in iter_sent if (words := find_sent(s.lower()))}

【讨论】:

    【解决方案2】:

    使用itertools 之类的东西可能有更有效的方法,但我不是很熟悉。

    test = {"dict_sentences":...} # I'm assuming it's a section of a json or a larger dictionary.
    
    output = {}
    j = 1
    for sent in test["dict_sentences"]:
        addition = []
        for i in list_of_words:
            if i.upper() in sent["text"].upper():
                addition.append(i)
        if addition:
            output[f"sent{j}"] = addition
            j += 1
    

    【讨论】:

      【解决方案3】:

      您可以进行嵌套的 dict 理解并通过将两者转换为小写来比较内容,例如:

      
      output = {
          f"sent{i+1}": [
              phrase for phrase in list_of_words if phrase.lower() in sentence['text'].lower()
          ] for i,sentence in enumerate(dict_sentences)
      }
      
      output_without_empty_matches = { k:v for k,v in output.items() if v }
      
      print(output_without_empty_matches)
      >>> {'sent1': ['churchill college', 'emmanuel college'], 'sent2': ['emmanuel college'], 'sent3': ['holy trinity church']}
      

      【讨论】:

        【解决方案4】:
        new_list=[]
        new_dict={}
        
        for index, subdict in enumerate(dict_sentences):
            for word in list_of_words:
                if word in subdict['text'].lower():
                    key="sent"+str(index+1)
                    new_list.append(word)
                    new_dict[key]=new_list
            new_list=[]
        
        print(new_dict)
        

        【讨论】:

          猜你喜欢
          • 2014-08-09
          • 2012-07-21
          • 1970-01-01
          • 2022-12-06
          • 1970-01-01
          • 2021-10-12
          • 1970-01-01
          • 2021-05-20
          • 2018-12-17
          相关资源
          最近更新 更多