【发布时间】: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