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.
19 scrap
.register_event("msg", markov_learn
)
20 scrap
.register_event("msg", markov_talk
)
21 scrap
.register_event("msg", markov_load
)
22 scrap
.register_event("msg", markov_dump
)
23 scrap
.register_event("msg", markov_stats
)
25 nickmatch
= re
.compile(scrap
.nickname
)
29 def markov_stats(c
,list,bot
):
32 cmd
= list[4].split(" ")[0]
34 if cmd
== "markov_stats":
35 c
.privmsg(list[5], "words: %d" % len(statetab
[("\n","\n")]))
36 c
.privmsg(list[5], "chains: %d" % len(statetab
.items()))
38 #loads in a previously pickled saved state
39 def markov_load(c
,list,bot
):
42 cmd
= list[4].split(" ")[0]
45 fp
= list[4].split(" ")[1]
49 statetab
= pickle
.load(pkfile
)
51 print "Could not load db: Doesn't exist\n"
54 #pickles out the state to a file
55 def markov_dump(c
,list,bot
):
58 cmd
= list[4].split(" ")[0]
61 fp
= list[4].split(" ")[1]
63 pkfile
= open(fp
,"w+")
65 pickle
.dump(statetab
,pkfile
)
67 def markov_learn(c
,list,bot
):
68 """ Should not be called directly """
70 words
= [x
for x
in list[4].split(" ") if not x
.isspace()]
78 #go through every word and put them in a hash table.
79 #EX the sentence "Mary had a little lamb"
80 #first iteration, w1 and w2 are both empty.
81 #statetab[w1][w2] doesn't exist, so make it and set
82 #statetab[""][""] to Mary.
84 #Then, set w1 to w2 and w2 to i, so the chain moves forward.
86 statetab
.setdefault((w1
,w2
),[]).append(i
)
89 statetab
.setdefault((w1
,w2
),[]).append("\n")
91 if nickmatch
.search(list[4]) and bot
.autorep
== 1 and random
.randint(0,3) == 0:
92 tmp
= emit_chain(random
.choice(list[4].split(" ")))
97 c
.privmsg(list[5], "%s: %s" % (list[0],tmp
))
101 if random
.randint(0,15) == 0 and bot
.talk
== 1:
102 c
.privmsg(list[5], "%s" % (emit_chain(random
.choice(list[4].split(" ")))))
115 #make the first word the key if its not a space
126 newword
= random
.choice(statetab
[(w1
,w2
)])
130 retval
= retval
+ newword
+ " "
135 #max of rand words if we don't hit a space or other error
136 if i
>= random
.randint(5,50):
141 def markov_talk(c
,list,bot
):
142 """ Makes the markov chain talk to you """
144 cmd
= list[4].split(" ")[0]
147 key
= list[4].split(" ")[1]
151 if list[3] and cmd
== "talk":
152 tmp
= emit_chain(key
);
155 c
.privmsg(list[5],"%s" % tmp
)