Python extracting sentence containing 2 words
Question: I have the same problem that was discussed in this link [Python extract
sentence containing word](http://stackoverflow.com/questions/16032832/python-
extract-sentence-containing-word), but the difference is that I want to find 2
words in the same sentence. I need to extract sentences from a corpus, which
contains 2 specific words. Does anyone could help me, please?


Answer: This would be simple using the
[TextBlob](https://textblob.readthedocs.org/en/latest/) package together with
Python's builtin [sets](http://docs.python.org/2/library/sets.html).

Basically, iterate through the sentences of your text, and check if their
exists an intersection between the set of words in the sentence and your
search words.

    
    
    from text.blob import TextBlob
    
    search_words = set(["buy", "apples"])
    blob = TextBlob("I like to eat apple. Me too. Let's go buy some apples.")
    matches = []
    for sentence in blob.sentences:
        words = set(sentence.words)
        if search_words & words:  # intersection
            matches.append(str(sentence))
    print(matches)
    # ["Let's go buy some apples."]
    

Update: Or, more Pythonically,

    
    
    from text.blob import TextBlob
    
    search_words = set(["buy", "apples"])
    blob = TextBlob("I like to eat apple. Me too. Let's go buy some apples.")
    matches = [str(s) for s in blob.sentences if search_words & set(s.words)]
    print(matches)
    # ["Let's go buy some apples."]
    

