homer512 icon

wc py

homer512 | PRO | 06/17/14 06:03:51 AM UTC | 0 ⭐ | 778 👁️ | Never ⏰ | []
Python |

860 B

|

None

|

0 👍

/

0 👎

"""see https://robotwhale.wordpress.com/2014/06/16/30-days-of-python-day-9-unix-tools-for-desert-island-coding-ii/
"""
 
def wc(path, lines=True, words=True, chars=True, bytes_=True):
    """Prints the line, word, char, and byte counts of a file"""
    operations = ((lines, lambda _: 1),
                  (words, lambda line: len(line.split())),
                  (chars, len),
                  (bytes_, len),
    )
    used_ops = [operation for used, operation in operations if used]
    sums = [0] * len(used_ops)
    with open(path,'r') as f_in:
        for line in f_in:
            for index, operation in enumerate(used_ops):
                sums[index] += operation(line)
    counts = [str(cnt) for cnt in sums]
    max_len = max([len(cnt) for cnt in counts])
    justified = [cnt.rjust(max_len) for cnt in counts]
    print str.join(' ', justified), path

Comments