我想弄清楚如何在匹配的单词前后提取3行。Python,在匹配前后提取3行
目前,我的词被发现。我写了一些文本来测试我的代码。而且,我想出了如何在比赛结束后打印三条线。
但是,我很难弄清楚如何在单词“secure
”之前打印三行。
这是我到目前为止有:
from itertools import islice
with open("testdoc.txt", "r") as f:
for line in f:
if "secure" in line:
print("".join(line))
print ("".join(islice(f,3)))
这里是我的测试中创建的文本:您需要缓冲你的线条,所以你可以记得他们
----------------------------
This is a test to see
if i can extract information
using this code
I hope, I try,
maybe secure shell will save thee
Im adding extra lines to see my output
hoping that it comes out correctly
boy im tired, sleep is nice
until then, time will suffice
你尝试过什么到目前为止不工作的第一个?我发现没有试图保留以前读取的行,以防在发现关键字时需要它们。 – Aaron