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


