-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpywc.py
106 lines (85 loc) · 3.15 KB
/
pywc.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import argparse
import codecs
# import timeit
# from functools import partial
class WC:
def __init__(self, files, count_lines, count_words, count_chars, count_bytes):
self.files = files
self.count_lines = count_lines
self.count_words = count_words
self.count_chars = count_chars
self.count_bytes = count_bytes
def count_file(self, file_path):
with codecs.open(file_path, "r", encoding="utf-8", errors="ignore") as file:
content = file.read()
if self.count_lines:
lines_count = content.count("\n")
else:
lines_count = None
if self.count_words:
words = content.split()
word_count = len(words)
else:
word_count = None
if self.count_chars:
char_count = len(content)
else:
char_count = None
if self.count_bytes:
byte_count = len(content.encode("utf-8"))
else:
byte_count = None
return lines_count, word_count, char_count, byte_count
def execute(self):
for file_path in self.files:
try:
lines_count, words_count, chars_count, byte_count = self.count_file(
file_path
)
output = ""
if lines_count is not None:
output += f"{lines_count}\t"
if words_count is not None:
output += f"{words_count}\t"
if chars_count is not None:
output += f"{chars_count}\t"
if byte_count is not None:
output += f"{byte_count}\t"
output += file_path
print(output)
except FileNotFoundError:
print(f"wc: {file_path}: No such file or directory")
def main():
parser = argparse.ArgumentParser(description="wc command replica")
parser.add_argument("files", metavar="FILE", nargs="+", help="input files")
parser.add_argument(
"-l", "--lines", action="store_true", help="print the newline counts"
)
parser.add_argument(
"-w", "--words", action="store_true", help="print the word counts"
)
parser.add_argument(
"-c", "--bytes", action="store_true", help="print the byte counts"
)
parser.add_argument(
"-m", "--chars", action="store_true", help="print the character counts"
)
args = parser.parse_args()
wc = WC(args.files, args.lines, args.words, args.chars, args.bytes)
wc.execute()
if __name__ == "__main__":
main()
# def measure_performance():
# # Create an instance of the WC class with your desired arguments
# wc = WC(
# files=["test.txt"],
# count_lines=True,
# count_words=True,
# count_chars=True,
# count_bytes=True,
# )
# # Measure the execution time of the execute() method of the WC class
# execution_time = timeit.timeit(partial(wc.execute), number=1)
# print(f"Execution time: {execution_time:.6f} seconds")
# if __name__ == "__main__":
# measure_performance()