-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathwc.py
More file actions
77 lines (61 loc) · 1.79 KB
/
Copy pathwc.py
File metadata and controls
77 lines (61 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import argparse
parser = argparse.ArgumentParser(
prog="wc",
description="Count lines, words and characters in files",
)
parser.add_argument(
"-l",
action="store_true",
help="Count lines only"
)
parser.add_argument(
"-w",
action="store_true",
help="Count words only"
)
parser.add_argument(
"-c",
action="store_true",
help="Count characters only",
)
parser.add_argument(
"paths",
nargs="+",
help="The file(s) to count",
)
args = parser.parse_args()
total_lines = 0
total_words = 0
total_chars = 0
counts = []
for path in args.paths:
with open(path, "r") as f:
content = f.read()
lines = len(content.splitlines())
words = len(content.split())
chars = len(content)
total_lines += lines
total_words += words
total_chars += chars
counts.append((lines, words, chars, path))
width_lines = max(len(str(total_lines)) + 1, 2)
width_words = max(len(str(total_words)) + 1, 3)
width_chars = max(len(str(total_chars)) + 1, 4)
for lines, words, chars, path in counts:
if args.l:
print(f"{lines:>{width_lines}} {path}")
elif args.w:
print(f"{words:>{width_words}} {path}")
elif args.c:
print(f"{chars:>{width_chars}} {path}")
else:
print(f"{lines:>{width_lines}}{words:>{width_words}}{chars:>{width_chars}} {path}")
if len(args.paths) > 1:
if args.l:
print(f"{total_lines:>{width_lines}} total")
elif args.w:
print(f"{total_words:>{width_words}} total")
elif args.c:
print(f"{total_chars:>{width_chars}} total")
else:
print(f"{total_lines:>{width_lines}}{total_words:>{width_words}}{total_chars:>{width_chars}} total")