我有这个脚本可以在文本中搜索单词。搜索进行得非常好,结果按预期工作。我要达到的目标是提取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'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句