Skip to content

Commit bf81772

Browse files
committed
finished wc.py
1 parent 3623a1d commit bf81772

File tree

1 file changed

+64
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+64
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser()
4+
parser.add_argument("files", nargs="+")
5+
parser.add_argument("-l", action="store_true", help="show line count")
6+
parser.add_argument("-w", action="store_true", help="show word count")
7+
parser.add_argument("-c", action="store_true", help="show byte count")
8+
9+
args = parser.parse_args()
10+
11+
show_lines = args.l
12+
show_words = args.w
13+
show_bytes = args.c
14+
15+
if not show_lines and not show_words and not show_bytes:
16+
show_lines = True
17+
show_words = True
18+
show_bytes = True
19+
20+
total_lines = 0
21+
total_words = 0
22+
total_bytes = 0
23+
24+
for file in args.files:
25+
try:
26+
f = open(file, "rb")
27+
content = f.read()
28+
f.close()
29+
30+
line_count = content.count(b"\n")
31+
word_count = len(content.split())
32+
byte_count = len(content)
33+
34+
total_lines += line_count
35+
total_words += word_count
36+
total_bytes += byte_count
37+
38+
output = []
39+
40+
if show_lines:
41+
output.append(str(line_count))
42+
if show_words:
43+
output.append(str(word_count))
44+
if show_bytes:
45+
output.append(str(byte_count))
46+
47+
output.append(file)
48+
print(" ".join(output))
49+
50+
except OSError:
51+
print("wc:", file, "not found")
52+
53+
if len(args.files) > 1:
54+
output = []
55+
56+
if show_lines:
57+
output.append(str(total_lines))
58+
if show_words:
59+
output.append(str(total_words))
60+
if show_bytes:
61+
output.append(str(total_bytes))
62+
63+
output.append("total")
64+
print(" ".join(output))

0 commit comments

Comments
 (0)