Skip to content

Commit 66b0147

Browse files
wc implemented and working for wc sample-files/*
1 parent d8dc9a7 commit 66b0147

File tree

1 file changed

+44
-6
lines changed
  • implement-shell-tools/wc

1 file changed

+44
-6
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,45 @@
1313

1414
args = parser.parse_args()
1515
file_paths = args.path
16+
lines_flag, words_flag, bytes_flag = args.lines, args.words, args.bytes
17+
18+
def format_output(details_list, totals=None):
19+
show_all = not (lines_flag or words_flag or bytes_flag)
20+
output_lines = []
21+
22+
# Per-file output
23+
for d in details_list:
24+
line = ""
25+
26+
if show_all or lines_flag:
27+
line += f"{d['line_count']:>3} "
28+
29+
if show_all or words_flag:
30+
line += f"{d['word_count']:>3} "
31+
32+
if show_all or bytes_flag:
33+
line += f"{d['file_size']:>3} "
34+
35+
line += d["file_path"]
36+
output_lines.append(line)
37+
38+
# Totals (only if more than one file)
39+
if totals and len(details_list) > 1:
40+
total_line = ""
41+
42+
if show_all or lines_flag:
43+
total_line += f"{totals['line_count']:>3} "
44+
45+
if show_all or words_flag:
46+
total_line += f"{totals['word_count']:>3} "
47+
48+
if show_all or bytes_flag:
49+
total_line += f"{totals['file_size']:>3} "
50+
51+
total_line += "total"
52+
output_lines.append(total_line)
53+
54+
return "\n".join(output_lines)
1655

1756
file_details_list = []
1857
line_count_total = 0
@@ -25,8 +64,8 @@
2564
content = f.read()
2665

2766
details = {
28-
"line_count": content.count("\n"), # matches real wc -l
29-
"word_count": len(content.split()), # split on whitespace
67+
"line_count": content.count("\n"),
68+
"word_count": len(content.split()),
3069
"file_size": os.path.getsize(file_path),
3170
"file_path": file_path,
3271
}
@@ -42,14 +81,13 @@
4281
"line_count": line_count_total,
4382
"word_count": word_count_total,
4483
"file_size": file_size_total,
45-
"file_path": "total"
4684
}
4785

86+
formatted_output = format_output(file_details_list, totals_details)
87+
print(formatted_output)
4888

49-
print(totals_details)
50-
51-
show_all = not (args.lines or args.words or args.bytes)
5289

5390

5491
# print(args)
5592

93+
# 1 4 20 sample-files/1.txt

0 commit comments

Comments
 (0)