-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathromscore.py
66 lines (54 loc) · 1.42 KB
/
romscore.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
import os
import pickle
import math
class RomScorer:
def __init__(self):
self._allwords = {}
self._allcount = 0
self._romwords = {}
self._romcount = 0;
self._processed_words = {}
def add_words(self, words):
for w in words:
if w not in self._allwords:
self._allwords[w] = 0
self._allwords[w] += 1
self._allcount += 1
def add_romwords(self, words):
for w in words:
if w not in self._romwords:
self._romwords[w] = 0
self._romwords[w] += 1
self._romcount += 1
def process(self):
for rw in self._romwords:
rs = self._romwords[rw] / self._romcount
if rw in self._allwords:
nrs = self._allwords[rw] / self._allcount
else:
nrs = 1 / self._allcount
score = math.log (rs / nrs)
self._processed_words[rw] = score
for nrw in self._allwords:
if nrw not in self._processed_words:
nrs = self._allwords[nrw] / self._allcount
score = math.log (1 / self._allcount)
self._processed_words[nrw] = score
def get_words_score(self, words):
score = 0
for w in words:
if w in self._processed_words:
score += self._processed_words[w]
return score
def save_cache(self, filename):
with open(filename, 'wb') as f:
cache = { 'words': self._processed_words }
pickle.dump(cache, f)
def load_cache(self, filename):
try:
with open(filename, 'rb') as f:
cache = pickle.load(f)
self._processed_words = cache['words']
return True
except:
return False