只是想更新Raymond Hettinger对 python 3 的精彩回答:
您所要做的就是更改izip
为zip
from re import finditer
from itertools import chain, islice, repeat, tee
def kwic(text, tgtword, width=20):
'Find all occurrences of tgtword and show the surrounding context'
matches = (mo.span() for mo in finditer(r"[A-Za-z\'\-]+", text))
padded = chain(repeat((0,0), width), matches, repeat((-1,-1), width))
t1, t2, t3 = tee((padded), 3)
t2 = islice(t2, width, None)
t3 = islice(t3, 2*width, None)
for (start, _), (i, j), (_, stop) in zip(t1, t2, t3):
if text[i: j] == tgtword:
context = text[start: stop]
yield context
此外,为了完整起见,两者NLTK
都Texacity
内置了此功能;但是,两者都不像雷蒙德的答案那样有效,因为两者都使用字符数作为 window 而不是tokens。
NLTK
import nltk
test = """
As soon as it had finished, all her blood rushed to her heart, for she was so angry to hear that Snow-White was yet living. "But now," thought she to herself, "will I make something which shall destroy her completely." Thus saying, she made a poisoned comb by arts which she understood, and then, disguising herself, she took the form of an old widow. She went over the seven hills to the house of the seven Dwarfs, and[15] knocking at the door, called out, "Good wares to sell to-day!"
"""
tokens = nltk.word_tokenize(test)
text = nltk.Text(tokens)
text.concordance('Snow-White', width=100)
Displaying 1 of 1 matches:
er heart , for she was so angry to hear that Snow-White was yet living . `` But now , '' thought she
文本性
from textacy.text_utils import KWIC
test = """
As soon as it had finished, all her blood rushed to her heart, for she was so angry to hear that Snow-White was yet living. "But now," thought she to herself, "will I make something which shall destroy her completely." Thus saying, she made a poisoned comb by arts which she understood, and then, disguising herself, she took the form of an old widow. She went over the seven hills to the house of the seven Dwarfs, and[15] knocking at the door, called out, "Good wares to sell to-day!"
"""
snow_white = KWIC(test, "Snow-White", window_width=50)
print(next(snow_white, ["Finished"]))
d to her heart, for she was so angry to hear that Snow-White was yet living. "But now," thought she to herself
['Finished']