您可以采取以下方法。这首先尝试将整个文本拆分为单词,并记录每个单词的索引。
接下来,它遍历文本以查找 test text,其间可能有 0 个或多个空格。对于每个匹配,它会记录开始,然后使用 Python 的 bisect 库创建在该点之前和之后找到的单词列表,以在 words 列表中找到所需的条目。
import bisect
import re
test = "aa bb cc dd test text ee ff gg testtextwith hh ii jj"
words = [(w.start(), w.group(0)) for w in re.finditer(r'(\b\w+?\b)', test)]
adjacent_words = 2
for match in re.finditer(r'(test\s*?text)', test):
start, end = match.span()
words_start = bisect.bisect_left(words, (start, ''))
words_end = bisect.bisect_right(words, (end, ''))
words_before = [w for i, w in words[words_start-adjacent_words : words_start]]
words_after = [w for i, w in words[words_end : words_end + adjacent_words]]
# Adjacent words as a list
print words_before, match.group(0), words_after
# Or, surrounding text as is.
print test[words[words_start-adjacent_words][0] : words[words_end+adjacent_words][0]]
print
所以对于这个有 2 个相邻单词的例子,你会得到以下输出:
['cc', 'dd'] test text ['ee', 'ff']
cc dd test text ee ff
['ff', 'gg'] testtext ['hh', 'ii']
ff gg testtextwith hh ii