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"]
しかし、@ jamylakのsplit
ベースのソリューションが高速であることに注意してください。
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
速度差が大きくなるため、より少ないが、それでも重要です文字列:
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
+1 nice answer! 'txt = txt * 10000'と'%timeit'を実行すると結果はより明確になります – Kent
ありがとうございました。大きな文字列には '%timeit'ベンチマークを追加しました。 – unutbu