-
Notifications
You must be signed in to change notification settings - Fork 2
/
ngram.py
66 lines (43 loc) · 993 Bytes
/
ngram.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 json
bigram = None
unigram = None
def load():
global bigram
global unigram
print("Loading N-gram databases...")
f = open("datasets/bigram.json", 'r')
bigram = json.load(f)
f.close()
f = open("datasets/unigram.json", 'r')
unigram = json.load(f)
f.close()
def rateSentence(words):
# copy, and add the end tags
words = list(words)
words.extend(("</s>", "</s>"))
rating = 0
total = 0
word1 = "<s>"
word2 = "<s>"
for word3 in words:
result = get_bigram_score(word1, word2, word3)
rating += result
if result > 0:
total += 1
# walk the buffers
word1 = word2
word2 = word3
return (total, rating)
def get_bigram_score(word1, word2, word3):
global bigram
if word1 in bigram:
if word2 in bigram[word1]:
if word3 in bigram[word1][word2]:
return bigram[word1][word2][word3]
return 0
def get_unigram_score(word1, word2):
global unigram
if word1 in unigram:
if word2 in unigram[word1]:
return unigram[word1][word2]
return 0