forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtf-25.py
More file actions
78 lines (66 loc) · 1.74 KB
/
tf-25.py
File metadata and controls
78 lines (66 loc) · 1.74 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
#!/usr/bin/env python
import sys, re, operator, string
#
# The Quarantine class for this example
#
class TFQuarantine:
def __init__(self, func):
self._funcs = [func]
def bind(self, func):
self._funcs.append(func)
return self
def execute(self):
def guard_callable(v):
return v() if hasattr(v, '__call__') else v
value = lambda : None
for func in self._funcs:
value = func(guard_callable(value))
print(guard_callable(value))
#
# The functions
#
def get_input(arg):
def _f():
return sys.argv[1]
return _f
def extract_words(path_to_file):
def _f():
with open(path_to_file) as f:
data = f.read()
pattern = re.compile('[\W_]+')
word_list = pattern.sub(' ', data).lower().split()
return word_list
return _f
def remove_stop_words(word_list):
def _f():
with open('../stop_words.txt') as f:
stop_words = f.read().split(',')
# add single-letter words
stop_words.extend(list(string.ascii_lowercase))
return [w for w in word_list if not w in stop_words]
return _f
def frequencies(word_list):
word_freqs = {}
for w in word_list:
if w in word_freqs:
word_freqs[w] += 1
else:
word_freqs[w] = 1
return word_freqs
def sort(word_freq):
return sorted(word_freq.items(), key=operator.itemgetter(1), reverse=True)
def top25_freqs(word_freqs):
top25 = ""
for tf in word_freqs[0:25]:
top25 += str(tf[0]) + ' - ' + str(tf[1]) + '\n'
return top25
#
# The main function
#
TFQuarantine(get_input)\
.bind(extract_words)\
.bind(remove_stop_words)\
.bind(frequencies)\
.bind(sort)\
.bind(top25_freqs)\
.execute()