duke
#!/usr/bin/python3.5
for line in open('test.txt'):
if 'duke' in line:
print(line)
一切都好。但是我怎么能在这个结果之前看到2行?
在grep中它是grep -B 2 "duke" test.txt
。我怎么能在python中做同样的事情?
答案 0 :(得分:1)
您可以使用固定大小为2的deque
:
#!/usr/bin/python3.5
from collections import deque
queue = deque(maxlen=2)
for line in open('test.txt'):
if 'duke' in line:
print(list(queue))
queue.append(line)
答案 1 :(得分:1)
你需要保留一个带有N个前面行的缓冲区(在这种情况下,N = 2)。例如:
N=2
buffer = []
for line in open('test.txt'):
buffer.append(line)
if len(buffer) > N:
buffer.pop(0)
if 'duke' in line:
print(buffer)