Skip to content

Commit 1e3fc25

Browse files
committed
implementation of wc with python
1 parent 80ca854 commit 1e3fc25

1 file changed

Lines changed: 104 additions & 0 deletions

File tree

implement-shell-tools/wc/my-wc.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#!/usr/bin/env python3
2+
3+
import sys
4+
import glob
5+
6+
def count_file(path):
7+
with open(path, "rb") as f:
8+
content = f.read()
9+
10+
byte_count = len(content)
11+
text = content.decode("utf-8", errors="ignore")
12+
13+
line_count = text.count("\n")
14+
word_count = len(text.split())
15+
16+
return line_count, word_count, byte_count
17+
18+
def expand(paths):
19+
files = []
20+
for p in paths:
21+
matches = glob.glob(p)
22+
if matches:
23+
files.extend(matches)
24+
else:
25+
files.append(p)
26+
return files
27+
28+
def main():
29+
args = sys.argv[1:]
30+
31+
show_l = False
32+
show_w = False
33+
show_c = False
34+
35+
paths = []
36+
37+
38+
# parse args
39+
for a in args:
40+
if a == "-l":
41+
show_l = True
42+
elif a == "-w":
43+
show_w = True
44+
elif a == "-c":
45+
show_c = True
46+
else:
47+
paths.append(a)
48+
49+
# default: show all
50+
if not (show_l or show_w or show_c):
51+
show_l = show_w = show_c = True
52+
53+
files = expand(paths)
54+
55+
total_l = 0
56+
total_w = 0
57+
total_c = 0
58+
59+
results = []
60+
61+
for file in files:
62+
try:
63+
l, w, c = count_file(file)
64+
except FileNotFoundError:
65+
print(f"wc: {file}: No such file or directory", file=sys.stderr)
66+
continue
67+
68+
total_l += l
69+
total_w += w
70+
total_c += c
71+
72+
results.append((l,w,c, file))
73+
74+
# print per-file results (GNU-aligned formatting)
75+
for l, w, c, file in results:
76+
77+
parts = []
78+
if show_l:
79+
parts.append(f"{l:3}")
80+
if show_w:
81+
parts.append(f"{w:4}")
82+
if show_c:
83+
parts.append(f"{c:4}")
84+
85+
86+
print("".join(parts) + " " + file)
87+
88+
# print total if multiple files
89+
if len(results) > 1:
90+
parts = []
91+
92+
if show_l:
93+
parts.append(f"{total_l:3}")
94+
if show_w:
95+
parts.append(f"{total_w:4}")
96+
if show_c:
97+
parts.append(f"{total_c:4}")
98+
99+
100+
print("".join(parts) + " total")
101+
102+
103+
if __name__ == "__main__":
104+
main()

0 commit comments

Comments
 (0)