-
Notifications
You must be signed in to change notification settings - Fork 0
/
wc.py
92 lines (73 loc) · 2.37 KB
/
wc.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
"""Completing a challenge to build my own version of a Unix wc tool from:
https://codingchallenges.fyi/challenges/challenge-wc/"""
import sys
import re
import os
def bytes_num(filepath: str) -> int:
"""Returns the number of bytes in a given file
Args:
filepath (str): the path to/name of the file
Returns:
int: number of bytes in the given file
"""
return os.stat(filepath).st_size
def file_lines(filepath: str) -> int:
"""Returns the number of lines in a given file
Args:
filepath (str): the path to/name of the file
Returns:
int: number of lines in the given file
"""
with open(filepath, 'r', encoding='UTF-8') as f:
lines = f.readlines()
return len(lines)
def num_words(filepath: str) -> int:
"""Returns the number of words in a given file
Args:
filepath (str): the path to/name of the file
Returns:
int: number of words in the given file
"""
with open(filepath, 'r', encoding='UTF-8') as f:
text = f.read()
words = text.split(' ')
return len(words)
def num_chars(filepath: str) -> int:
"""Returns the number of characters in a given file
Args:
filepath (str): the path to/name of the file
Returns:
int: number of characters in the given file
"""
with open(filepath, 'r', encoding='UTF-8') as f:
text = f.read()
return len(text)
def main():
"""Main entry point to handle the arguments and options as well as output
"""
args = ''.join(i + ' ' for i in sys.argv[1:])
try:
opts = re.search(r'\A-[clwmCLWM]', args).group()
except AttributeError:
opts = 'clw'
try:
filepath = re.search(r'[a-zA-Z]+[.][a-zA-Z]+', args).group()
except AttributeError:
filepath = "test.txt"
output = []
if 'c' in opts.lower():
bytes = bytes_num(filepath)
output.append(bytes)
if 'l' in opts.lower():
lines = file_lines(filepath)
output.append(lines)
if 'w' in opts.lower():
words = num_words(filepath)
output.append(words)
if 'm' in opts.lower():
chars = num_chars(filepath)
output.append(chars)
output.append(filepath)
print(*output, sep=" ")
if __name__ == '__main__':
main()