Search code examples
pythonlistmatchsentence

Get the most matching sentence in a list


How to find the most matching sentence in another sentence?

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` 
    '''

I'm looking for a function which will check whether all the words are present in the sentence or not.

Desired result is: 2


Solution

  • 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)