Python grep word和show word在这个词之前

时间:2017-05-31 11:17:02

标签: python for-loop grep

我应该找点线。我写了剧本。我有一个文件,我应该找到行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中做同样的事情?

2 个答案:

答案 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)