DeaD_EyE

head_tail_count.py

May 2nd, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. from contextlib import redirect_stdout
  5. from pathlib import Path
  6. from collections import deque
  7.  
  8.  
  9. def help():
  10.     with redirect_stdout(sys.stderr):
  11.         print('This programm counts the words in a file')
  12.         print('The command head counts the words in the first n lines')
  13.         print('The command tail counts the words in the last n lines\n')
  14.         print(sys.argv[0], '<head|tail> <file> <n-lines>')
  15.     sys.exit(1)
  16.  
  17.  
  18. def get_args():
  19.     try:
  20.         exe, cmd, file, n = sys.argv
  21.     except ValueError:
  22.         help()
  23.     if not cmd in ('head', 'tail'):
  24.         help()
  25.     try:
  26.         n = int(n)
  27.     except ValueError:
  28.         help()
  29.     try:
  30.         file = Path(file)
  31.     except ValueError:
  32.         print('The path is invalid', file=sys.stderr)
  33.         sys.exit(2)
  34.     if not file.exists():
  35.         print('The file does not exist', file=sys.stderr)
  36.         sys.exit(3)
  37.     cmd = globals().get(cmd)
  38.     return cmd, file, n
  39.  
  40.  
  41. def head(iterable, n=1):
  42.     for element, _ in zip(iterable, range(n)):
  43.         yield element
  44.  
  45.  
  46. def tail(iterable, n=1):
  47.     hist = deque(maxlen=n)
  48.     for element in iterable:
  49.         hist.append(element)
  50.     yield from hist
  51.  
  52.  
  53. def count_words(func, file, n):
  54.     word_count = 0
  55.     with open(file) as fd:
  56.         for line in func(fd, n):
  57.             word_count += len(line.split())
  58.     print(f'{word_count} words in {n} line(s)')
  59.  
  60.  
  61. if __name__ == '__main__':
  62.     cmd, file, n = get_args()
  63.     count_words(cmd, file, n)
Add Comment
Please, Sign In to add comment