Advertisement
nher1625

Searching through text files for text pattern match

Mar 25th, 2015
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. __author__ = 'Work'
  2. '''
  3. You want to keep a limited history of the last few items seen during iteration or during some other kind of processing.
  4.  
  5. Keeping a limited history is a perfect use for a collections.deque. For example, the following code performs a simple text match
  6. on a sequence of lines and yields the matching line along with N previous lines of context when found:
  7. '''
  8.  
  9. #http://pymotw.com/2/collections/deque.html
  10. from collections import deque
  11.  
  12. def search(lines, pattern, history=5):
  13.     previous_lines = deque(maxlen=history)
  14.     for line in lines:
  15.         if pattern in line:
  16.             yield line, previous_lines
  17.         previous_lines.append(line)
  18.  
  19. # Example use on a file.
  20. if __name__ == '__main__':
  21.     with open('somefile.txt') as f:
  22.         for line, prevlines in search(f, 'line', 5):
  23.             for pline in prevlines:
  24.                 print(pline, end='')
  25.             print(line, end='')
  26.             print('-'*20)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement