liveBook · Manning

Wc utility

As explained in The Quick Python Book, Fourth Edition

The wc utility is a Unix command-line tool that counts lines, words, and bytes in files or input streams and can report the maximum line length.

The Unix `wc` utility counts lines, words, and bytes in a file. It is a useful target for a small command-line program: count the input, then decide which results to display. section 11.5 section 13.10.1

Output depends on the options:

Implementing the option rule

In Python, define each option as an `argparse` boolean that defaults to `False`. If none is selected, enable the three default counts; otherwise print only selected results. Track the longest line by comparing its length with the current maximum as each line is read. Test the result against the system’s `wc` command. section 11.5.2 section 11.5

#!/usr/bin/env python3
# File: word_count_program.py
""" Reads a file and returns the number of lines, words,
    and characters - similar to the UNIX wc utility
"""
import sys
import argparse
 
 
def main():
    # initialze counts
    line_count = 0
    word_count = 0
    char_count = 0
    longest_line = 0
 
    parser = argparse.ArgumentParser(usage=__doc__)
    parser.add_argument("-c", "--characters",
                  action="store_true", dest="chars", default=False,
                  help="display number of characers")
    parser.add_argument("-w", "--words",
                  action="store_true", dest="words", default=False,
                  help="display number of words")
    parser.add_argument("-l", "--lines",
                  action="store_true", dest="lines", default=False,
                  help="display number of lines")
    parser.add_argument("-L", "--longest",
                  action="store_true", dest="longest", default=False,
                  help="display longest line length")
    parser.add_argument("filename", help="read data from this file")
    args = parser.parse_args()
 
    filename = args.filename    # open the file
    with  open(filename) as infile:
        for line in infile:
            line_count += 1
            char_count += len(line)
            words = line.split()
            word_count += len(words)
            if len(line) > longest_line:                        #1
                longest_line = len(line)
 
    default_args = any([getattr(args, _) for _ in ('chars', 'words',
                        'lines', 'longest')])                   #2
 
    if not default_args:
        args.chars = args.lines = args.words = True             #3
  
    if args.lines:
        print(f"{line_count:3}", end=" ")                       #4
    if args.words:
        print(f"{word_count:4}", end=" ")
    if args.chars:
        print(f"{char_count:4}", end=" ")
    if args.longest:
        print(f'{longest_line}', end=" ")
    print(f'{filename}')
if __name__ == '__main__':
    main()

The Python listing shows the command-line parser and count variables for a `wc`-like program. section 11.5.2

A closer Unix-compatible version also needs standard input and output redirection. Take care with `-c`: a character count in text mode can differ from a byte count for Unicode input. Distinguishing bytes (`-c`) from characters (`-m`) is a separate, harder extension. section 13.10.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through option defaults and longest-line tracking, while deferring byte-versus-character handling as a harder extension.
Examples
Uses Python `argparse` implementations and comparison with a system `wc` command.
What it assumes
Assumes an earlier file-counting program; concentrates on refactoring its command-line options rather than teaching counting from zero.
What you can do after
Build it from scratch as a Python command-line counter with selectable totals and an optional longest-line result.
How it connects
Connects file processing with command-line options, `argparse`, standard input and output, and Unicode byte-versus-character counts.

Also explained in

Compare how 2 books explain wc utility →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.