python - 查找子字符串周围的单词

标签 python regex string algorithm

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

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() )

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

最佳答案

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

关于python - 查找子字符串周围的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515707/

相关文章:

javascript - JS 的参数 - 哪个是最好的方法?

android - 在此行 : 找到多个注释

ruby - 将字符串拆分为值数组

python - 将 methodcaller 和 attrgetter 与排序相结合

python - 如何使异步任务/协程返回值被分配

python - 如何根据 pep8 在 Python 中的函数定义中换行?

jquery - 如何在 jQuery 中添加日期和整数

python - 将 zip 解压缩到内存,解析内容

java - 将输出分成 4 张椅子和蛮力方法的 block

regex - 如何设置 sklearn CountVectorizer 以包含非字母数字字符作为特征提取?