Skip to content

Commit 83a2a74

Browse files
committed
Complete wc.py implementation.
1 parent b711630 commit 83a2a74

2 files changed

Lines changed: 77 additions & 14 deletions

File tree

implement-shell-tools/cat/cat.py

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,3 @@
1919
print(line, end="")
2020
else:
2121
print(line, end = "")
22-
23-
# # file = open(filename)
24-
25-
# if sys.argv[1]== "-n":
26-
# line_number = 1
27-
# for line in file:
28-
# print(line_number, line, end = "")
29-
# line_number += 1
30-
# else:
31-
# for line in file:
32-
# print(line, end = "")
33-
34-
35-

implement-shell-tools/wc/wc.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import sys
2+
import os
3+
4+
count_lines = "-l" in sys.argv
5+
count_words = "-w" in sys.argv
6+
count_bytes = "-c" in sys.argv
7+
filenames = []
8+
9+
for argument in sys.argv[1:]:
10+
if not argument.startswith("-"):
11+
filenames.append(argument)
12+
13+
total_lines = 0
14+
total_words = 0
15+
total_bytes = 0
16+
17+
for filename in filenames:
18+
file = open(filename)
19+
20+
line_count = 0
21+
word_count = 0
22+
23+
for line in file:
24+
line_count += 1
25+
word_count += len(line.split())
26+
byte_count = os.path.getsize(filename)
27+
28+
total_lines += line_count
29+
total_words += word_count
30+
total_bytes += byte_count
31+
32+
output = []
33+
34+
if count_lines:
35+
output.append(line_count)
36+
37+
if count_words:
38+
output.append(word_count)
39+
40+
if count_bytes:
41+
output.append(byte_count)
42+
43+
44+
if not count_lines and not count_words and not count_bytes:
45+
output.append(line_count)
46+
output.append(word_count)
47+
output.append(byte_count)
48+
49+
formatted_output = []
50+
51+
for number in output:
52+
formatted_output.append(f"{number:3}")
53+
54+
print(" ".join(formatted_output), filename)
55+
56+
if len(filenames) > 1:
57+
total_output = []
58+
59+
if count_lines:
60+
total_output.append(total_lines)
61+
62+
if count_words:
63+
total_output.append(total_words)
64+
65+
if count_bytes:
66+
total_output.append(total_bytes)
67+
68+
if not count_lines and not count_words and not count_bytes:
69+
total_output.append(total_lines)
70+
total_output.append(total_words)
71+
total_output.append(total_bytes)
72+
73+
formatted_total = []
74+
75+
for number in total_output:
76+
formatted_total.append(f"{number:3}")
77+
print(" ".join(formatted_total), "total")

0 commit comments

Comments
 (0)