首页 > 解决方案 > 获取列表中最匹配的句子

问题描述

如何在另一个句子中找到最匹配的句子?

matchSentence = ["weather in", "weather at", "weather on"]
sentence = "weather on monday"

for item in matchSentence:
    ''' here get the index of the `item` 
    if all the words are in the `item` is in the `sentence` 
    '''

我正在寻找一个函数来检查所有单词是否都存在于sentence

期望的结果是:2

标签: pythonlistmatchsentence

解决方案


matchSentence = ["weather in", "weather at", "weather on"]
sentence = "weather on monday"

maxCount = 0
maxCntInd = -1
words1 = sentence.split()  # list of all words in sentence
wordSet1 = set(words1)

for item in matchSentence:
    ''' here get the index of the `item`
    if all the words are in the `item.split()` is in the `sentence`
    '''
    words2 = item.split()  # list of all words in item
    wordSet2 = set(words2)

    commonWords = len(wordSet2.intersection(wordSet1))
    if commonWords >= maxCount:
        maxCount = commonWords
        maxCntInd = matchSentence.index(item)

print(maxCntInd)

推荐阅读