Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'Work'
- '''
- You want to keep a limited history of the last few items seen during iteration or during some other kind of processing.
- Keeping a limited history is a perfect use for a collections.deque. For example, the following code performs a simple text match
- on a sequence of lines and yields the matching line along with N previous lines of context when found:
- '''
- #http://pymotw.com/2/collections/deque.html
- 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)
- # Example use on a file.
- if __name__ == '__main__':
- with open('somefile.txt') as f:
- for line, prevlines in search(f, 'line', 5):
- for pline in prevlines:
- print(pline, end='')
- print(line, end='')
- print('-'*20)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement