Skip to content

Commit f0bacb0

Browse files
committed
Implement wc command in Python
1 parent 62f7818 commit f0bacb0

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import argparse
2+
import re
3+
4+
parser = argparse.ArgumentParser(
5+
prog="check-for-wc",
6+
description="Implement my own version of wc",
7+
)
8+
9+
parser.add_argument("paths", nargs="+", help="The file paths to process")
10+
parser.add_argument("-l", action="store_true", help="Counts the total number of lines")
11+
parser.add_argument("-c", action="store_true", help="Counts the total number of characters")
12+
parser.add_argument("-w", action="store_true", help="Counts the total number of words")
13+
14+
args = parser.parse_args()
15+
16+
paths = args.paths
17+
show_lines = args.l
18+
show_words = args.w
19+
show_char = args.c
20+
21+
no_flags_given = not show_lines and not show_words and not show_char
22+
23+
columns = []
24+
25+
for path in paths:
26+
with open(path, "r", encoding="utf-8") as f:
27+
content = f.read()
28+
29+
line_count = content.count("\n")
30+
31+
word_count = len([word for word in re.split(r"\s+", content) if word != ""])
32+
33+
char_count = len(content.encode("utf-8"))
34+
35+
columns.append({
36+
"path": path,
37+
"lines": line_count,
38+
"words": word_count,
39+
"char": char_count,
40+
})
41+
42+
if len(columns) > 1:
43+
total_lines = 0
44+
total_words = 0
45+
total_char = 0
46+
47+
for result in columns:
48+
total_lines += result["lines"]
49+
total_words += result["words"]
50+
total_char += result["char"]
51+
52+
columns.append({
53+
"path": "total",
54+
"lines": total_lines,
55+
"words": total_words,
56+
"char": total_char,
57+
})
58+
59+
for result in columns:
60+
line = ""
61+
if no_flags_given or show_lines:
62+
line += str(result["lines"]).rjust(6, " ")
63+
if no_flags_given or show_words:
64+
line += str(result["words"]).rjust(6, " ")
65+
if no_flags_given or show_char:
66+
line += str(result["char"]).rjust(6, " ")
67+
68+
line += " " + result["path"]
69+
70+
print(line)

0 commit comments

Comments
 (0)