Skip to content

Commit 4b98427

Browse files
committed
implement wc CLI
1 parent a49c91e commit 4b98427

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(prog= "wc",
4+
description="Count lines, words, and characters in one or more files.")
5+
6+
parser.add_argument("-c",action="store_true",help="Count the number of characters.")
7+
parser.add_argument("-w",action="store_true", help="Count the number of words.")
8+
parser.add_argument("-l",action="store_true",help="Count the number of lines.")
9+
parser.add_argument("paths",nargs="+",help="Path(s) to the file(s) to process.")
10+
11+
12+
total_results = {
13+
14+
}
15+
16+
17+
args =parser.parse_args()
18+
paths= args.paths;
19+
no_flags = not args.c and not args.w and not args.l
20+
21+
for path in paths:
22+
with open(path, "r") as f:
23+
content = f.read()
24+
25+
count_lines = len(content.splitlines())
26+
count_words = len(content.split())
27+
count_characters = len(content)
28+
29+
results = {}
30+
31+
if no_flags or args.l:
32+
results["count_lines"] = count_lines
33+
34+
if no_flags or args.w:
35+
results["count_words"] = count_words
36+
37+
if no_flags or args.c:
38+
results["count_characters"] = count_characters
39+
40+
for key, value in results.items():
41+
total_results[key] = total_results.get(key, 0) + value
42+
43+
print(" ".join(map(str, results.values())), path)
44+
45+
if len(paths) > 1:
46+
print(" ".join(map(str, total_results.values())), "total")
47+

0 commit comments

Comments
 (0)