#保存有限的历史记录,匹配当前行和最后检查过的N行文本
from collections import deque
def search(lines,pattern,history=5) :
previous_lines = deque(maxlen = history)
for line in lines :
if pattern in line :
yield line,previous_lines
previous_lines.append(line)
#print (previous_lines,"++++")
#Example use on a file
if __name__ == "__main__" :
with open ("somefile.txt") as f :
for line,prevlines in search(f,'python',5) :
for pline in prevlines :
print(pline,end="")
#pass
print (line,end="")
print ("-"*20)
############
#补充说明:
q = deque(maxlen=3)
q.append(1)##类似于list,不过只保留最新出现的3个元素###在最后面插入元素####
q.appendleft(4)###在最前插入###
q.pop()####后面弹出一个
q.popleft()####前面弹出一个