16

テキストから指定された単語を含むすべての文を抽出しようとしています。

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

しかし、それは私を返しています:

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

それ以外の :

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

何か助けてください?

4

7 に答える 7

32

正規表現は必要ありません:

>>> 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."]
于 2013-04-16T09:07:14.570 に答える
20
In [3]: re.findall(r"([^.]*?apple[^.]*\.)",txt)                                                                                                                             
Out[4]: ['I like to eat apple.', " Let's go buy some apples."]
于 2013-04-16T09:09:20.783 に答える
9
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
于 2013-04-16T09:07:00.647 に答える