From 228b0797287f598ecc095711af59fa4b61d376dc Mon Sep 17 00:00:00 2001 From: Owen Dorweiler Date: Sun, 23 Feb 2025 18:28:34 -0500 Subject: [PATCH] Homework 04: wc.py --- homework04/wc.py | 49 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) mode change 100644 => 100755 homework04/wc.py diff --git a/homework04/wc.py b/homework04/wc.py old mode 100644 new mode 100755 index 67b4ee3..0d9bb6b --- a/homework04/wc.py +++ b/homework04/wc.py @@ -27,7 +27,13 @@ def count_stream(stream=sys.stdin) -> dict[str, int]: >>> count_stream(io.StringIO('Despite all my rage, I am still just a rat in a cage')) {'newlines': 1, 'words': 13, 'bytes': 52} ''' - pass + counts = {'newlines': 0, 'words': 0, 'bytes': 0} + for line in stream: + counts['newlines'] += 1 + counts['bytes'] += len(line.encode('utf-8')) # found this byte-counting solution online + words = line.split() + counts['words'] += len(words) + return counts def print_counts(counts: dict[str, int], options: list[str]) -> None: ''' Print the newline, word, and byte counts. If none of the options are @@ -39,7 +45,30 @@ def print_counts(counts: dict[str, int], options: list[str]) -> None: >>> print_counts({'newlines': 1, 'words': 13, 'bytes': 52}, ['newlines', 'words', 'bytes']) 1 13 52 ''' - pass + + output_order = ['newlines', 'words', 'bytes'] + counts_to_print = [] + + if not options: + options = output_order + + # Add selected counts to counts_to_print + for option in output_order: + if option in options: + counts_to_print.append(counts[option]) + + # This calculates the width based off of all the the counts + if len(counts_to_print) > 1: + max_all = max(counts.values()) + count_width = len(str(max_all)) + else: + count_width = 0 + + # Format the selected counts and join with spaces + formatted_counts = [str(count).rjust(count_width) for count in counts_to_print] + + output_string = ' '.join(formatted_counts) + print(output_string) # Main Execution @@ -53,10 +82,22 @@ def main(arguments=sys.argv[1:], stream=sys.stdin) -> None: 1 13 52 ''' # Parse command line arguments - pass + options = [] + for arg in arguments: + if arg in ('-h', '--help'): + usage(0) + elif arg in ('-c', '--bytes'): + options.append('bytes') + elif arg in ('-l', '--lines'): + options.append('newlines') + elif arg in ('-w', '--words'): + options.append('words') + else: + usage(1) # Count stream and print counts - pass + counts = count_stream(stream) + print_counts(counts, options) if __name__ == '__main__': main()