Created
November 16, 2013 05:46
-
-
Save zpconn/7496449 to your computer and use it in GitHub Desktop.
A random text generator based on an N=2 Markov chain model.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
import random | |
class Markov: | |
memory = defaultdict(list) | |
separator = ' ' | |
def get_initial(self): | |
return (' ', ' ') | |
def break_text(self, txt): | |
prev = self.get_initial() | |
for word in txt.split(self.separator): | |
yield prev, word | |
prev = (prev[1], word) | |
yield prev, '' | |
def learn(self, txt): | |
for part in self.break_text(txt): | |
key = part[0] | |
value = part[1] | |
self.memory[key].append(value) | |
def step(self, state): | |
choice = random.choice(self.memory[state] or ['']) | |
if not choice: | |
return None | |
next_state = (state[1], choice) | |
return choice, next_state | |
def ask(self, seed=None): | |
ret = [] | |
if not seed: | |
seed = self.get_initial() | |
while True: | |
link = self.step(seed) | |
if link is None: | |
break | |
ret.append(link[0]) | |
seed = link[1] | |
return self.separator.join(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment