# 导入队列
from collections import deque
def search(lines, pattern, history=5):
# 固定长度的队列
pre_lines = deque(maxlen=history) # 新的元素加入,如果队列已满,最老的元素会自动被移除
for line in lines:
if pattern in line:
pre_lines.append(line)
yield line, pre_lines
def dequeDemo():
p = deque()
p.append('a')
print(p)
p.append('b')
print(p)
p.appendleft('a1')
print(p)
p.pop()
print(p)
p.popleft()
print(p)
if __name__ == '__main__':
"""
文本的内容如下:
a b c python d
e
f g h e python
j k l m python n
o p python q r
s1 t python u
s2 t python u
s3 t python u
"""
with open(r'./dequedemo.txt') as f:
for line, pre_lines in search(f, 'python'):
for pl in pre_lines:
print(pl, end='')
print('line=', line, end='')
print('-' * 20)
dequeDemo()