我希望能够在文档中搜索给定的字符串并找到每个实例的上下文。例如,在文档中搜索“Figure”并返回该字符串后面的 X 个字符(从“Figure-1 Super awesome figure. next sentence”返回“-1 Super awesome figure”)
我知道如何打印:A)该字符串的每个实例
mystring = "Figure"
with open('./mytext.txt', 'r') as searchfile:
for line in searchfile:
if mystring in line:
print(mystring)
但这无济于事;或 B)包含该字符串的每一行
for line in open('./mytext.txt', "r"):
if "Figure" in line:
print(line)
它返回整行中的所有文本,之前和之后,这对我的目的来说很麻烦。
我可以在“mystring”处拆分一行并在拆分后返回 X 个字符吗?还是有更好的方法?