-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweightedWordGenerator.py
More file actions
53 lines (41 loc) · 1.64 KB
/
weightedWordGenerator.py
File metadata and controls
53 lines (41 loc) · 1.64 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
import sys, histogram, random, math
def generateRandomWordFromHistogram(_histogram):
totalWords = 0
listOfTuples = []
for word, count in _histogram:
# add word to tuple with it's range (being it's upper bound)
upperBound = totalWords + count
listOfTuples.append((word, upperBound))
totalWords += count
# generate random int and then binary search to find the word it correlates to
randomInt = random.randint(1, totalWords)
word = binarySearch(listOfTuples, randomInt)
return word
def binarySearch(tuples, index):
half = math.floor(len(tuples) / 2)
midpointIndexOfTuplesList = int(half)
if midpointIndexOfTuplesList == 1:
word = tuples[midpointIndexOfTuplesList][0]
return word
midpointOfTuplesList = tuples[midpointIndexOfTuplesList]
lowerBoundOfMidpoint = tuples[midpointIndexOfTuplesList - 1][1]
upperBoundOfMidpoint = midpointOfTuplesList[1]
if lowerBoundOfMidpoint <= index <= upperBoundOfMidpoint:
return tuples[midpointIndexOfTuplesList][0]
elif index < lowerBoundOfMidpoint:
upperBound = midpointIndexOfTuplesList - 1
return binarySearch(tuples[0:upperBound], index)
elif upperBoundOfMidpoint < index:
upperBound = midpointIndexOfTuplesList - 1
return binarySearch(tuples[midpointIndexOfTuplesList:-1], index)
def generateSentenceFromTextfile(textfile):
_histogram = histogram.generateHistogramFromFile(textfile)
sortedHistogram = histogram.sortHistogram(_histogram)
sentence = []
for i in range(7):
randomWord = generateRandomWordFromHistogram(sortedHistogram)
sentence.append(randomWord)
return (' ').join(sentence)
if __name__ == "__main__":
_file = sys.argv[1]
print generateSentenceFromTextfile(_file)