Python extract sentence containing word

user2187202 picture user2187202 · Apr 16, 2013 · Viewed 28.7k times · Source

I am trying to extract all the sentence containing a specified word from a text.

txt="I like to eat apple. Me too. Let's go buy some apples."
txt = "." + txt
re.findall(r"\."+".+"+"apple"+".+"+"\.", txt)

but it is returning me :

[".I like to eat apple. Me too. Let's go buy some apples."]

instead of :

[".I like to eat apple., "Let's go buy some apples."]

Any help please ?

Answer

jamylak picture jamylak · Apr 16, 2013

No need for regex:

>>> txt = "I like to eat apple. Me too. Let's go buy some apples."
>>> [sentence + '.' for sentence in txt.split('.') if 'apple' in sentence]
['I like to eat apple.', " Let's go buy some apples."]