forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtf-33-active.py
More file actions
83 lines (71 loc) · 2.21 KB
/
tf-33-active.py
File metadata and controls
83 lines (71 loc) · 2.21 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
79
80
81
#!/usr/bin/env python
import sys, operator, string, os, threading, re
from util import getch, cls, get_input
from time import sleep
lock = threading.Lock()
#
# The active view
#
class FreqObserver(threading.Thread):
def __init__(self, freqs):
threading.Thread.__init__(self)
self.daemon,self._end = True, False
# freqs is the part of the model to be observed
self._freqs = freqs
self._freqs_0 = sorted(self._freqs.items(), key=operator.itemgetter(1), reverse=True)[:25]
self.start()
def run(self):
while not self._end:
self._update_view()
sleep(0.1)
self._update_view()
def stop(self):
self._end = True
def _update_view(self):
lock.acquire()
freqs_1 = sorted(self._freqs.items(), key=operator.itemgetter(1), reverse=True)[:25]
lock.release()
if (freqs_1 != self._freqs_0):
self._update_display(freqs_1)
self._freqs_0 = freqs_1
def _update_display(self, tuples):
def refresh_screen(data):
# clear screen
cls()
print(data)
sys.stdout.flush()
data_str = ""
for (w, c) in tuples:
data_str += str(w) + ' - ' + str(c) + '\n'
refresh_screen(data_str)
#
# The model
#
class WordsCounter:
freqs = {}
def count(self):
def non_stop_words():
stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase))
for line in f:
yield [w for w in re.findall('[a-z]{2,}', line.lower()) if w not in stopwords]
words = next(non_stop_words())
lock.acquire()
for w in words:
self.freqs[w] = 1 if w not in self.freqs else self.freqs[w]+1
lock.release()
#
# The controller
#
print("Press space bar to fetch words from the file one by one")
print("Press ESC to switch to automatic mode")
model = WordsCounter()
view = FreqObserver(model.freqs)
with open(sys.argv[1]) as f:
while get_input():
try:
model.count()
except StopIteration:
# Let's wait for the view thread to die gracefully
view.stop()
sleep(1)
break