Skip to content

Commit 33da6dc

Browse files
committed
Implement wc command with py
1 parent dc22267 commit 33da6dc

File tree

1 file changed

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

1 file changed

+69
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import argparse
2+
3+
4+
parser = argparse.ArgumentParser(
5+
prog="Implment wc command",
6+
description="Count lines, words, and characters in text files."
7+
)
8+
9+
parser.add_argument("paths", nargs='+', type=str, help="The path to process")
10+
parser.add_argument('-l', action="store_true", help='Ouput number of lines')
11+
parser.add_argument('-w', action="store_true", help='Ouput number of words')
12+
parser.add_argument('-c', action="store_true", help='Ouput number of characters')
13+
14+
args = parser.parse_args()
15+
is_lines_option = args.l
16+
is_words_option = args.w
17+
is_chars_option = args.c
18+
output_list = []
19+
output_total=[]
20+
total_lines = 0
21+
total_words = 0
22+
total_chars = 0
23+
24+
for path in args.paths:
25+
with open(path, 'r') as f:
26+
content= f.read()
27+
28+
line_count = content.count('\n')
29+
word_count = len(content.split())
30+
char_count = len(content)
31+
32+
total_lines += line_count
33+
total_words += word_count
34+
total_chars += char_count
35+
36+
file_output = []
37+
38+
if not (args.l or args.w or args.c):
39+
file_output = [str(line_count), str(word_count), str(char_count)]
40+
else:
41+
if args.l:
42+
file_output.append(str(line_count))
43+
if args.w:
44+
file_output.append(str(word_count))
45+
if args.c:
46+
file_output.append(str(char_count))
47+
48+
file_output.append(path)
49+
output_list.append(" ".join(file_output))
50+
51+
print("\n".join(output_list))
52+
53+
54+
55+
if len(args.paths) > 1:
56+
if not (args.l or args.w or args.c):
57+
output_total = [str(total_lines), str(total_words), str(total_chars)]
58+
59+
else:
60+
if args.l:
61+
output_total.append(str(total_lines))
62+
if args.w:
63+
output_total.append(str(total_words))
64+
if args.c:
65+
output_total.append(str(total_chars))
66+
67+
output_total.append("total")
68+
print(" ".join(output_total))
69+

0 commit comments

Comments
 (0)