Homework 04: wc.py

This commit is contained in:
Owen Dorweiler 2025-02-23 18:28:34 -05:00 committed by Mayleen Liu
commit 228b079728

49
homework04/wc.py Normal file → Executable file
View file

@ -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()