Skip to content

Commit d613e7a

Browse files
committed
Implement wc shell tool in Python
1 parent b547925 commit d613e7a

File tree

1 file changed

+70
-0
lines changed
  • implement-shell-tools/implement-shell-tools-python/wc

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/env python3
2+
import sys
3+
4+
def count_file_content(content):
5+
raw_lines = content.split("\n")
6+
lines = len(raw_lines) - 1 if raw_lines[-1] == "" else len(raw_lines)
7+
words = len(content.split())
8+
bytes_ = len(content.encode("utf-8"))
9+
return lines, words, bytes_
10+
11+
12+
def print_counts(path, counts, options):
13+
parts = []
14+
if options["line"]:
15+
parts.append(str(counts[0]).rjust(8))
16+
if options["word"]:
17+
parts.append(str(counts[1]).rjust(8))
18+
if options["byte"]:
19+
parts.append(str(counts[2]).rjust(8))
20+
21+
output = "".join(parts)
22+
print(f"{output} {path}")
23+
24+
25+
def main():
26+
args = sys.argv[1:]
27+
28+
options = {"line": False, "word": False, "byte": False}
29+
files = []
30+
31+
for arg in args:
32+
if arg == "-l":
33+
options["line"] = True
34+
elif arg == "-w":
35+
options["word"] = True
36+
elif arg == "-c":
37+
options["byte"] = True
38+
else:
39+
files.append(arg)
40+
41+
if not files:
42+
print("No files specified", file=sys.stderr)
43+
sys.exit(1)
44+
45+
if not any(options.values()):
46+
options = {"line": True, "word": True, "byte": True}
47+
48+
total = [0, 0, 0]
49+
multiple = len(files) > 1
50+
51+
for path in files:
52+
try:
53+
with open(path, "r", encoding="utf-8") as f:
54+
content = f.read()
55+
56+
counts = count_file_content(content)
57+
total = [t + c for t, c in zip(total, counts)]
58+
59+
print_counts(path, counts, options)
60+
61+
except Exception as e:
62+
print(f"Error reading file {path}: {e}", file=sys.stderr)
63+
sys.exit(1)
64+
65+
if multiple:
66+
print_counts("total", total, options)
67+
68+
69+
if __name__ == "__main__":
70+
main()

0 commit comments

Comments
 (0)