提取搜索词周围的词


问题内容

我有这个脚本可以在文本中搜索单词。搜索进行得非常好,结果按预期工作。我想要达到的目标是提取n接近比赛的单词。例如:

世界是一个很小的地方,我们应该努力照顾它。

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

left -> [is, a, small]
right -> [we, should, try]

最好的方法是什么?

谢谢!


问题答案:
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:]

这使您可以指定要捕获的任何一方的单词数。它通过动态构造正则表达式来工作。用

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