-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathUntitled-2.py
More file actions
44 lines (32 loc) · 999 Bytes
/
Copy pathUntitled-2.py
File metadata and controls
44 lines (32 loc) · 999 Bytes
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
# -*- coding: utf-8 -*-
import os
import sys
import collections
import string
def analyze_text(data):
res = {}
res["total_lines"] = data.count(os.linesep)
res["total_characters"] = len(data.replace(" ", "")) - res["total_lines"]
counter = collections.Counter(data.split())
d = counter.most_common()
res["total_words"] = sum(i[1] for i in d)
res["unique_words"] = len(i[0] for i in d)
special_chars = string.punctuation
res["special_characters"] = sum(
v for k, v in collections.Counter(data).items() if k in special_chars
)
return res
def main():
script_name = sys.argv[0]
try:
textfile = sys.argv[1]
with open(textfile, "r", encoding="utf_8") as f:
data = f.read()
res = analyze_text(data)
print(res)
except IndexError:
print('Usage: %s TEXTFILE' % script_name)
except IOError:
print('"%s" cannot be opened.' % textfile)
if __name__ == "__main__":
main()