-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathwc.py
More file actions
78 lines (56 loc) · 1.8 KB
/
Copy pathwc.py
File metadata and controls
78 lines (56 loc) · 1.8 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
78
import argparse
import glob
# create parser
parser = argparse.ArgumentParser(description="Simple wc tool")
parser.add_argument("files", nargs="+", help="files to read")
parser.add_argument("-l", action="store_true", help="count lines")
parser.add_argument("-w", action="store_true", help="count words")
parser.add_argument("-c", action="store_true", help="count characters")
args = parser.parse_args()
# expand *.txt
def get_files(file_patterns):
files = []
for pattern in file_patterns:
matched = glob.glob(pattern)
if matched:
files.extend(matched)
else:
files.append(pattern)
return files
def count_file(file_name):
try:
with open(file_name, "r") as f:
text = f.read()
lines = text.count("\n")
words = len(text.split())
chars = len(text)
return lines, words, chars
except FileNotFoundError:
print(f"Error: {file_name} not found")
return 0, 0, 0
def print_result(lines, words, chars, file_name):
# if no flags → show all
if not args.l and not args.w and not args.c:
print(lines, words, chars, file_name)
else:
output = []
if args.l:
output.append(str(lines))
if args.w:
output.append(str(words))
if args.c:
output.append(str(chars))
output.append(file_name)
print(" ".join(output))
# main
files = get_files(args.files)
total_lines = total_words = total_chars = 0
for file in files:
lines, words, chars = count_file(file)
total_lines += lines
total_words += words
total_chars += chars
print_result(lines, words, chars, file)
# if multiple files → show total
if len(files) > 1:
print_result(total_lines, total_words, total_chars, "total")