📜  包含所有给定短语的句子

📅  最后修改于: 2021-06-29 11:47:21             🧑  作者: Mango

给定一个句子列表和一个短语列表。任务是查找哪些句子包含一个短语中的所有单词,并为每个短语打印包含给定短语的句子编号。

约束:一个单词不能超过10个句子。

例子:

方法:对于每个短语,我们必须找到包含该短语所有单词的句子。因此,对于给定短语中的每个单词,我们检查一个句子是否包含该单词。我们为每个句子执行此操作。如果句子中的单词存储在集合中而不是列表中,则此搜索过程可能会变得更快。

下面是上述方法的实现:

# Python program to find the sentence
# that contains all the given phrases 
def getRes(sent, ph):
    sentHash = dict()
  
    # Loop for adding hased sentences to sentHash
    for s in range(1, len(sent)+1):
        sentHash[s] = set(sent[s-1].split())
          
    # For Each Phrase
    for p in range(0, len(ph)):
        print("Phrase"+str(p + 1)+":")
  
        # Get the list of Words
        wordList = ph[p].split()
        res = []
  
        # Then Check in every Sentence
        for s in range(1, len(sentHash)+1):
            wCount = len(wordList)
  
            # Every word in the Phrase
            for w in wordList:
                if w in sentHash[s]:
                    wCount -= 1
  
            # If every word in phrase matches
            if wCount == 0:
  
            # add Sentence Index to result Array
                res.append(s)
        if(len(res) == 0):
            print("NONE")
        else:
            print('% s' % ' '.join(map(str, res)))
  
# Driver Function
def main():
    sent = ["Strings are an array of characters",
    "Sentences are an array of words"]
    ph = ["an array of", "sentences are strings"]
    getRes(sent, ph)
  
main()
输出:
Phrase1:
1 2
Phrase2:
NONE