Maximum line length is the length of the longest line in a text input. In a Python command-line program modeled on `wc`, it can be reported alongside line, word, and character counts. The `-L` option selects it explicitly; unlike the three standard counts, it is not included when no options are given. section 11.5.2 section 11.5
Track the longest line
Start with `longest_line = 0`. As each line is read, compare its length with `longest_line` and keep the larger value. For lines read as `"cat\n"` and `"elephant\n"`, applying `len` to each line gives 4 and 9, so the maximum is 9. This follows the shown approach of measuring the lines as read, including their newline characters. section 11.5.2 section 11.5.2
# wc.py
import argparse
def count_stats(file_path):
with open(file_path) as infile:
lines = infile.readlines()
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines)
char_count = sum(len(line) for line in lines)
max_line_length = max(len(line) for line in lines)
return line_count, word_count, char_count, max_line_length
def main():
parser = argparse.ArgumentParser(description=
'Count lines, words, and characters in a file.')
parser.add_argument('file', help='File to count')
parser.add_argument('-l', '--lines', action='store_true',
help='Count lines')
parser.add_argument('-w', '--words', action='store_true',
help='Count words')
parser.add_argument('-c', '--chars', action='store_true',
help='Count characters')
parser.add_argument('-L', '--max-line-length', action='store_true',
help='Print length of the longest line')
args = parser.parse_args()
line_count, word_count, char_count, max_line_length = count_stats(args.file)
if args.lines:
print(f'Lines: {line_count}')
if args.words:
print(f'Words: {word_count}')
if args.chars:
print(f'Characters: {char_count}')
if args.max_line_length:
print(f'Max line length: {max_line_length}')
if __name__ == '__main__':
main()
The listing offers a compact alternative: read the lines, then calculate `max(len(line) for line in lines)` alongside the other file statistics. Unlike a running maximum initialized to zero, this expression needs a nonempty collection of lines. section 11.5.2
