/
markov.py
executable file
·78 lines (68 loc) · 2.45 KB
/
markov.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
#!/usr/bin/python
"""
markovChain class attempts to produce a obj_list of resultects that
matches pattern of inputted obj_list of resultects
"""
import queue
import tools
import random
class markov_chain:
def __init__(self, obj_list, level=1):
self.level = level
self.obj_list = obj_list
self.pair_tb = {}
self.__fill_pair_tb(obj_list)
#need a random obj to start off
#TODO: need to change random start else it'll stay the same per generation
self.start = random.choice(obj_list)
#returns a randomly generated list of objects based on
#pair_tb
def generate_obj_list(self, count = 10):
cache = queue.Queue(self.level)
obj_list = []
#randomly generate the first word
start = random.choice(self.obj_list)
obj_list.append(start)
cache.put(start)
for x in range(1, count):
pattern = [obj for obj in cache.queue]
#returns longest pattern from history
while not tuple(pattern) in self.pair_tb:
pattern.pop()
new_obj = tools.weighted_choice(self.pair_tb[tuple(pattern)])
obj_list.append(new_obj)
#updates cache
if cache.full():
cache.get()
cache.put(new_obj)
return obj_list
def __fill_pair_tb(self, obj_list):
#cache stores words read until full and then
#stores in m_raw_count_tb
temp_caches = []
#generate caches
for x in range(1,self.level + 1):
temp_caches.append(queue.Queue(x))
for result in obj_list:
for c in temp_caches:
if c.full():
pattern = tuple(c.queue)
if pattern in self.pair_tb:
if result in self.pair_tb[pattern]:
self.pair_tb[pattern][result] += 1
else:
self.pair_tb[pattern][result] = 1
else:
self.pair_tb[pattern] = {}
self.pair_tb[pattern][result] = 1
#removes first item and put result at the end
c.get()
c.put(result)
else:
c.put(result)
def __debug_pair_tb(self):
for i in self.pair_tb:
for o in i:
print(i)
print(o)
print (self.pair_tb[i][o])