This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
214 lines (159 loc) · 5.44 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import os
import nltk
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from itertools import *
import copy
import random
import pickle
import pprint
from collections import OrderedDict
trivialTokenizer = RegexpTokenizer(r"\d+|Mr\.|Mrs\.|Dr\.|\b[A-Z]\.|[a-zA-Z_]+-[a-zA-Z_]+-[a-zA-Z_]+|[a-zA-Z_]+-[a-zA-Z_]+|[a-zA-Z_]+|--|'s|'t|'d|'ll|'m|'re|'ve|[.,:!?;\"'()\[\]&@#-]")
WORD_TYPE_COUNT = 12000
# Create an initialized model where everything is 0
model = {}
def dictCopy(item):
temp = {}
newCopy = {}
temp = item
newCopy = temp
return newCopy
def removeKey(mDict, key):
r = dict(mDict)
del r[key]
return r
def weighted_choice(choices, prob):
r = random.uniform(0.0, prob)
upto = 0
for c in choices.items():
if upto + c[1] >= r:
return c[0]
upto += c[1]
def file_input(userPath):
path = input(userPath)
if os.path.isdir(path):
return path
else:
return file_input('Enter an existing file directory: ')
# SANITY CHECK (THERE IS NO SANITY LEFT IN US)
def getMaxProb(unigram):
probability = 0
for word in model[unigram].items():
probability += word[1]
return probability
userEntry = 'N'
if os.path.exists('model.pickle'):
userEntry = input("Use pickled dictionary? (Y/N)")
if userEntry == 'Y' or userEntry == 'y':
with open('model.pickle', 'rb') as handle:
model = pickle.load(handle)
else:
directory = file_input('Enter a directory: ')
trainingData = []
for file in os.listdir(directory):
if file.endswith('.txt'):
fileData = open(directory + '\\' + file).read()
trainingData += fileData
else:
print('Found non-txt file: ' + file)
trainingData = ''.join(trainingData)
# Begin tokenizing
trainingData = trivialTokenizer.tokenize(trainingData)
unigramCount = len(trainingData)
freqDist = nltk.FreqDist(trainingData)
commonFreqDist = nltk.FreqDist(trainingData).most_common(WORD_TYPE_COUNT)
bigrams = nltk.bigrams(trainingData)
# For each bigram, we sort by the first word
vWordTypes = []
sortedBigramDict = {}
for x in commonFreqDist:
vWordTypes.append(x[0])
for word in bigrams:
x = False
y = False
if word[0] in vWordTypes:
x = True
if word[1] in vWordTypes:
y = True
tempList = []
if x == True and y == True:
if word[0] in sortedBigramDict:
tempList = sortedBigramDict[word[0]]
tempList.append(word[1])
sortedBigramDict[word[0]] = tempList
# print(sortedBigramDict) 'leisurely': ['walk', 'turns', 'turns', 'blah', 'etc'],
# Creating an empty slate
vTypeDict = {}
for v in vWordTypes:
vTypeDict[v] = 0
for v in vWordTypes:
# Copy temporary dictionary
tempDict = {}
tempDict = dictCopy(vTypeDict)
# Copy sorted bigram list
if v in sortedBigramDict:
tempList = []
tempList = dictCopy(sortedBigramDict[v])
for x in tempList:
if x != v:
tempDict[x] += 1
# ------------ Smoothing
# Get list of bigrams with counts 1-9
lowFreqBigramCount = 0
for bigram in tempDict.items():
if bigram[1] <= 9 and bigram[1] > 0:
lowFreqBigramCount += 1
# Increase each bigram count by 1/lowFreqBigramCount
additiveBigram = 0
if lowFreqBigramCount != 0:
additiveBigram = 1/lowFreqBigramCount
for bigram in tempDict.items():
tempDict[bigram[0]] += additiveBigram
# Increase each unigram count by V/lowFreqBigramCount
currentUnigramCount = 0
additiveUnigram = 0
if lowFreqBigramCount != 0:
additiveUnigram = WORD_TYPE_COUNT / lowFreqBigramCount
currentUnigramCount = freqDist[v] + additiveUnigram
# Probabilities
for bigram in tempDict.items():
if currentUnigramCount != 0:
tempDict[bigram[0]] /= currentUnigramCount
model[v] = tempDict
with open('model.pickle', 'wb') as handle:
pickle.dump(model, handle, protocol=pickle.HIGHEST_PROTOCOL)
#pprint.pprint(model['these'])
#print(model['plot'])
# Sentence generation
print("Generating sentence...")
# Pick a random word
sentence = []
# Grab random first word and append
currentWord = random.choice(list(model.keys()))
sentence.append(currentWord)
print('Initial Rand: ', currentWord)
sentence_finished = False
while not sentence_finished:
r = random.random()
accumulator = .0
#orderedModel = OrderedDict(sorted(model[currentWord].items(), key=lambda kv: kv[1], reverse=True))
for word in model[currentWord]:
accumulator += model[currentWord][word]
if accumulator >= r:
if word != currentWord:
sentence.append(word)
currentWord = word
break
if(len(sentence) >= 30):
sentence_finished = True
print(' '.join(sentence))
print(sentence)
sentenceBigrams = nltk.bigrams(sentence)
sentenceProbability = 1.0
for bigram in sentenceBigrams:
print(model[bigram[0]][bigram[1]])
sentenceProbability *= model[bigram[0]][bigram[1]]
print(sentenceProbability)
# Calculating probability of sentences
sentenceOne = "Go to the park and meet girls"
sentenceTwo = "No, I'm not paying for the damage to your car"