提取搜索词周围的单词

Pep*_*zza 7 python regex text-processing find

我有这个脚本在文本中进行单词搜索.搜索结果非常好,结果按预期工作.我想要实现的是提取n接近匹配的单词.例如:

世界是一个小地方,我们应该尽力照顾它.

假设我正在寻找place,我需要提取右边的3个单词和左边的3个单词.在这种情况下,他们将是:

left -> [is, a, small]
right -> [we, should, try]
Run Code Online (Sandbox Code Playgroud)

这样做的最佳方法是什么?

谢谢!

Hen*_*nyH 14

def search(text,n):
    '''Searches for text, and retrieves n words either side of the text, which are retuned seperatly'''
    word = r"\W*([\w]+)"
    groups = re.search(r'{}\W*{}{}'.format(word*n,'place',word*n), text).groups()
    return groups[:n],groups[n:]
Run Code Online (Sandbox Code Playgroud)

这允许您指定要捕获的任意一侧的单词数.它通过动态构造正则表达式来工作.同

t = "The world is a small place, we should try to take care of it."
search(t,3)
(('is', 'a', 'small'), ('we', 'should', 'try'))
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,小修正:函数应该是`def search(text,target,n)`和't'应该是`groups = re.search(r'{}\W*{} {}'中的"text".格式(WORD*N,目标,字*N),文本).groups()` (6认同)
  • 如果您搜索“The”,它会抛出错误,因为它找不到前面的 3 个单词 - 如何更正该错误,以便返回尽可能多的单词(本例中为 0 个单词)。另外,是否可以使搜索不区分大小写? (2认同)

ins*_*get 5

虽然正则表达式可以工作,但我认为这对于这个问题来说太过分了。最好使用两个列表推导式:

sentence = 'The world is a small place, we should try to take care of it.'.split()
indices = (i for i,word in enumerate(sentence) if word=="place")
neighbors = []
for ind in indices:
    neighbors.append(sentence[ind-3:ind]+sentence[ind+1:ind+4])
Run Code Online (Sandbox Code Playgroud)

请注意,如果您要查找的单词在句子中连续出现多次,则该算法会将连续出现的单词作为邻居包含在内。
例如:

在 [29] 中:邻居 = []

在[30]中:sentence = '世界是一个小地方地方地方,我们应该尽量照顾它。'.split()

In [31]: 句子 Out[31]: ['The', 'world', 'is', 'a', 'small', 'place', 'place', 'place,', 'we', '应该', '尝试', 'to', 'take', 'care', 'of', 'it.']

In [32]: indices = [i for i,word in enumerate(sentence) if word == 'place']

In [33]: for ind in indices:
   ....:     neighbors.append(sentence[ind-3:ind]+sentence[ind+1:ind+4])


In [34]: neighbors
Out[34]: 
[['is', 'a', 'small', 'place', 'place,', 'we'],
 ['a', 'small', 'place', 'place,', 'we', 'should']]
Run Code Online (Sandbox Code Playgroud)


per*_*eal 5

import re
s='The world is a small place, we should try to take care of it.'
m = re.search(r'((?:\w+\W+){,3})(place)\W+((?:\w+\W+){,3})', s)
if m:
    l = [ x.strip().split() for x in m.groups()]
left, right = l[0], l[2]
print left, right
Run Code Online (Sandbox Code Playgroud)

输出

['is', 'a', 'small'] ['we', 'should', 'try']
Run Code Online (Sandbox Code Playgroud)

如果你搜索The,它会产生:

[] ['world', 'is', 'a']
Run Code Online (Sandbox Code Playgroud)