3

我必须在一个大字符串中的子字符串匹配之前和之后提取两个单词。例如:

sub = 'name'

str = '''My name is Avi. Name identifies who you are. It is important to have a name starting with the letter A.'''

现在我必须在 str 中找到所有出现的 sub ,然后返回以下内容:

(My name is Avi), (Name identifies who), (have a name starting with)

请注意,如果 re 是字符串之后的句号,则仅返回字符串之前的单词,如上例所示。

我试过什么?

>>> import re
>>> text = '''My name is Avi. Name identifies who you are. It is important to have a name starting with the letter A.'''
>>> for m in re.finditer( 'name', text ):
...     print( 'name found', m.start(), m.end() )

这给了我匹配子字符串的开始和结束位置。我无法进一步了解如何在它周围找到单词。

4

2 回答 2

5
import re
sub = '(\w*)\W*(\w*)\W*(name)\W*(\w*)\W*(\w*)'
str1 = '''My name is Avi. Name identifies who you are. It is important to have a name starting with the letter A.'''
for i in re.findall(sub, str1, re.I):
    print " ".join([x for x in i if x != ""])

输出

My name is Avi
Name identifies who
have a name starting with

或者,

sub = '\w*\W*\w*\W*name\W*\w*\W*\w*'
for i in re.findall(sub, str1, re.I):
    i=i.strip(" .")
    print i
于 2013-05-13T06:37:32.743 回答
4

我提出了严重的丑陋:

(([^\s.]+)\s+)?(([^\s.]+)\s+)?(name[^\w\s]*)(\s+([^\s.]+))?(\s+([^\s.]+))?

确认在http://www.regexpal.com/上工作

该单元(([^\s.]+)\s+)匹配一个单词(定义为非空格 non- .)然后匹配一个空格序列(the \s+),并且完全是可选的。

(name[^\w\s]*)是您要搜索的关键字,后跟 0 个或多个非单词字符非空格(以便匹配name.name!例如)

因此,我们的策略是明确地将我们想要的关键字前后最多两个单词放入使用的正则表达式中。

确保设置了这个正则表达式:http re.IGNORECASE: //docs.python.org/2/library/re.html#re.IGNORECASE

我还没有测试过这个正则表达式在大量文本上是否很慢。

顺便说一句,如果关键字只能是一个字长,那么有一个更简单的解决方案:split您传入的字符串 on " ",然后对于您的关键字在拆分词中的每个实例,也最多抓取两个词 before 和 after 和joinon " "。这将更容易阅读、理解、维护和解释。

于 2013-05-13T06:11:21.470 回答