Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extract sentence containing word

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 ?

like image 265
user2187202 Avatar asked Apr 16 '13 09:04

user2187202


4 Answers

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."]
like image 191
jamylak Avatar answered Nov 10 '22 08:11

jamylak


In [3]: re.findall(r"([^.]*?apple[^.]*\.)",txt)                                                                                                                             
Out[4]: ['I like to eat apple.', " Let's go buy some apples."]
like image 21
Kent Avatar answered Nov 10 '22 08:11

Kent


In [7]: import re

In [8]: txt=".I like to eat apple. Me too. Let's go buy some apples."

In [9]: re.findall(r'([^.]*apple[^.]*)', txt)
Out[9]: ['I like to eat apple', " Let's go buy some apples"]

But note that @jamylak's split-based solution is faster:

In [10]: %timeit re.findall(r'([^.]*apple[^.]*)', txt)
1000000 loops, best of 3: 1.96 us per loop

In [11]: %timeit [s+ '.' for s in txt.split('.') if 'apple' in s]
1000000 loops, best of 3: 819 ns per loop

The speed difference is less, but still significant, for larger strings:

In [24]: txt = txt*10000

In [25]: %timeit re.findall(r'([^.]*apple[^.]*)', txt)
100 loops, best of 3: 8.49 ms per loop

In [26]: %timeit [s+'.' for s in txt.split('.') if 'apple' in s]
100 loops, best of 3: 6.35 ms per loop
like image 9
unutbu Avatar answered Nov 10 '22 07:11

unutbu


You can use str.split,

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

>>> [ t for t in txt.split('. ') if 'apple' in t]
['I like to eat apple', "Let's go buy some apples."]
like image 4
Adem Öztaş Avatar answered Nov 10 '22 09:11

Adem Öztaş