Much better text generation.
[scrappy.git] / modules / markov.py
blob8a155927e1d3805bbec3db18801860526567df96
1 #markov module for scrappy
3 #the inspiration for this code comes from
4 #"The Practice of Programming", so some of the variable
5 #names and such will be similar.
7 import random
9 statetab = {}
11 word1 = word2 = " "
13 def __init__(scrap):
14 scrap.register_msg_event(markov_learn)
15 scrap.register_msg_event(markov_talk)
17 random.seed()
19 def markov_learn(c,list,bot):
20 """ Should not be called directly """
21 words = list[4].split(" ")
22 w1 = w2 = " "
23 global statetab
24 global statetab_size
26 for i in words:
27 try:
28 statetab[w1][w2] = i
29 except KeyError:
30 statetab[w1] = {}
31 statetab[w1][w2] = i
33 (w1, w2) = (w2, i)
35 try:
36 statetab[w1][w2] = " "
37 except KeyError:
38 statetab[w1] = {}
39 statetab[w1][w2] = " "
41 if random.randint(0,10) == 0:
42 c.privmsg(list[5], "%s: %s" % (list[0], emit_chain(" ")))
44 def emit_chain(key):
45 global statetab
46 global word1
48 retval = ""
50 if key != " ":
51 word1 = key
53 # for i in range(random.randint(1,4)):
54 # for i in range(int(20)):
55 while 1:
56 try:
57 suffix = statetab[word1]
58 except KeyError:
59 word1 = random.choice(statetab.keys())
60 # return "wah?"
61 # continue
62 return retval
64 try:
65 t = random.choice(suffix.keys())
66 except IndexError:
67 word1 = random.choice(statetab.keys())
68 return "Not enough entropy."
70 if t == " ":
71 return retval
73 word1 = t
75 retval = retval + suffix[t] + " "
77 return retval
79 def markov_talk(c,list,bot):
80 """ Makes the markov chain talk to you """
82 cmd = list[4].split(" ")[0]
84 try:
85 key = list[4].split(" ")[1]
86 except IndexError:
87 key = " "
89 if list[3] and cmd == "talk":
90 c.privmsg(list[5],"%s" % emit_chain(key))