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:
- With no options, display line, word, and count totals. section 11.5
- Use `-l`, `-w`, or `-c` to request only the corresponding counts; multiple options display the selected counts. section 11.5 section 11.5.2
- Use `-L` to request the longest line length. It is never part of the default output. section 11.5 section 11.5.2
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

