Advertisement
homer512

wc py

Jun 17th, 2014
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. """see https://robotwhale.wordpress.com/2014/06/16/30-days-of-python-day-9-unix-tools-for-desert-island-coding-ii/
  2. """
  3.  
  4. def wc(path, lines=True, words=True, chars=True, bytes_=True):
  5.     """Prints the line, word, char, and byte counts of a file"""
  6.     operations = ((lines, lambda _: 1),
  7.                   (words, lambda line: len(line.split())),
  8.                   (chars, len),
  9.                   (bytes_, len),
  10.     )
  11.     used_ops = [operation for used, operation in operations if used]
  12.     sums = [0] * len(used_ops)
  13.     with open(path,'r') as f_in:
  14.         for line in f_in:
  15.             for index, operation in enumerate(used_ops):
  16.                 sums[index] += operation(line)
  17.     counts = [str(cnt) for cnt in sums]
  18.     max_len = max([len(cnt) for cnt in counts])
  19.     justified = [cnt.rjust(max_len) for cnt in counts]
  20.     print str.join(' ', justified), path
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement