Python extracting sentence containing 2 words

前端 未结 3 1778
逝去的感伤
逝去的感伤 2021-01-28 22:24

I have the same problem that was discussed in this link Python extract sentence containing word, but the difference is that I want to find 2 words in the same sentence. I need t

3条回答
  •  灰色年华
    2021-01-28 23:18

    If this is what you mean:

    import re
    txt="I like to eat apple. Me too. Let's go buy some apples."
    define_words = 'some apple'
    print re.findall(r"([^.]*?%s[^.]*\.)" % define_words,txt)  
    
    Output: [" Let's go buy some apples."]
    

    You can also try with:

    define_words = raw_input("Enter string: ")
    

    Check if the sentence contain the defined words:

    import re
    txt="I like to eat apple. Me too. Let's go buy some apples."
    words = 'go apples'.split(' ')
    
    sentences = re.findall(r"([^.]*\.)" ,txt)  
    for sentence in sentences:
        if all(word in sentence for word in words):
            print sentence
    

提交回复
热议问题