Skip to content

Commit 5981cd7

Browse files
committed
Added a helper function to Format the output
1 parent 53a9aa9 commit 5981cd7

1 file changed

Lines changed: 23 additions & 33 deletions

File tree

implement-shell-tools/wc/my_wc.py

Lines changed: 23 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,9 @@
1010
parser.add_argument("-c", "--character", action="store_true", help="Count characters")
1111

1212
args = parser.parse_args()
13-
file_paths = args.paths
1413

15-
# Fallback: if no options passed, show all
16-
show_line = args.line
17-
show_word = args.word
18-
show_char = args.character
19-
show_all = not (show_line or show_word or show_char)
14+
# If no flags are set, show all
15+
show_all = not (args.line or args.word or args.character)
2016

2117
# Count content in a string
2218
def count_content(content):
@@ -25,16 +21,23 @@ def count_content(content):
2521
characters = len(content)
2622
return len(lines), len(words), characters
2723

28-
# Totals for multiple files
29-
total = {
30-
"lines": 0,
31-
"words": 0,
32-
"characters": 0
33-
}
24+
# Format output line based on flags
25+
def format_output(lines, words, chars, label):
26+
parts = []
27+
if args.line or show_all:
28+
parts.append(f"{lines:8}")
29+
if args.word or show_all:
30+
parts.append(f"{words:8}")
31+
if args.character or show_all:
32+
parts.append(f"{chars:8}")
33+
parts.append(label)
34+
return " ".join(parts)
3435

36+
# Totals for multiple files
37+
total = {"lines": 0, "words": 0, "characters": 0}
3538
file_count = 0
3639

37-
for input_path in file_paths:
40+
for input_path in args.paths:
3841
try:
3942
if os.path.isdir(input_path):
4043
print(f"{input_path} is a directory. Skipping.")
@@ -50,29 +53,16 @@ def count_content(content):
5053
total["characters"] += characters
5154
file_count += 1
5255

53-
# Prepare output per file
54-
output_parts = []
55-
if show_line or show_all:
56-
output_parts.append(f"{lines:8}")
57-
if show_word or show_all:
58-
output_parts.append(f"{words:8}")
59-
if show_char or show_all:
60-
output_parts.append(f"{characters:8}")
61-
62-
output_parts.append(input_path)
63-
print(" ".join(output_parts))
56+
print(format_output(lines, words, characters, input_path))
6457

6558
except Exception as e:
6659
print(f'Error reading "{input_path}": {e}', file=sys.stderr)
6760

6861
# Print totals if more than one file processed
6962
if file_count > 1:
70-
output_parts = []
71-
if show_line or show_all:
72-
output_parts.append(f"{total['lines']:8}")
73-
if show_word or show_all:
74-
output_parts.append(f"{total['words']:8}")
75-
if show_char or show_all:
76-
output_parts.append(f"{total['characters']:8}")
77-
output_parts.append("total")
78-
print(" ".join(output_parts))
63+
print(format_output(
64+
total["lines"],
65+
total["words"],
66+
total["characters"],
67+
"total"
68+
))

0 commit comments

Comments
 (0)