需求:从文本somefile.txt 中查找关键字’python’所在的行,打印该行内容,并记录打印该行前5行数据。
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history) #创建固定长度默认=5的序列,当有新记录加入时自动移除最老的记录
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
if __name__ == '__main__':
with open('somefile.txt',encoding='utf-8') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-'*20)
相关知识: deque
In [19]: from collections import deque
In [20]: q = deque(maxlen = 3) #创建固定长度=3的序列,当由新记录加入时自动移除最老的记录
In [21]: q
Out[21]: deque([])
In [22]: q.append(1)
In [24]: q.append(2)
In [25]: q.append(3)
In [26]: q
Out[26]: deque([1, 2, 3])
In [27]: q.append(4)
In [28]: q
Out[28]: deque([2, 3, 4])
#如果不执行队列大小,则得到一个无限界队列,也可以在两端执行添加和弹出操作
In [29]: q = deque()
In [30]: q.append(1)
In [31]: q.append(2)
In [32]: q.append(3)
In [33]: q
Out[33]: deque([1, 2, 3])
In [34]: q.appendleft(4)
In [35]: q
Out[35]: deque([4, 1, 2, 3])
In [36]: q.pop()
Out[36]: 3
In [37]: q
Out[37]: deque([4, 1, 2])
In [38]: q.popleft()
Out[38]: 4
In [39]: q
Out[39]: deque([1, 2])
从队列两端添加或弹出元素的复杂度都是O(1), 这和列表不同,当从列表的头部插入或移除元素时,列表的复杂度为O(N)。