python - 获取列表中最匹配的句子
问题描述
如何在另一个句子中找到最匹配的句子?
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
解决方案
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)
推荐阅读
- arrays - Removing specific Value from an array using .remove() . But why im not getting the correct answer?
- php - 我可以在哪里放置在我的 laravel 应用程序上生成 pdf 响应的逻辑?
- javascript - Which is the easiest way to call a functional component in button onClick in React js
- java - Hazelcast优雅方式处理com.hazelcast.nio.serialization.HazelcastSerializationException java.io.InvalidClassException
- r - 如何从表达式创建 data.frame?
- angular - 您在预期流的位置提供了“未定义”。HttpInterceptor 中的错误
- python - for 循环在我的 discord.py 机器人中运行得太快
- c# - 从 Collider2D 数组中获取位置
- java - 即使根线程引用了其子对象之一,GC 根线程不再可以访问父对象是否符合 Java GC 的条件?
- c++ - 不同硬件上的不同 OpenGL 行为