Skip to content

Instantly share code, notes, and snippets.

@thommiller
Created October 3, 2017 18:23
A Python Implementation of a Markov Chain Text Generator
import random
class Markov(object):
def __init__(self, open_file):
self.dist = {}
self.open_file = open_file
self.words = self.split_to_words()
self.word_size = len(self.words)
self.create_distribution()
def split_to_words(self):
self.open_file.seek(0)
data = self.open_file.read()
words = data.split()
return words
def triples(self):
if len(self.words) < 3:
return
for i in range(len(self.words) - 2):
yield (self.words[i], self.words[i+1], self.words[i+2])
def create_distribution(self):
for w1, w2, w3 in self.triples():
key = (w1, w2)
if key in self.dist:
self.dist[key].append(w3)
else:
self.dist[key] = [w3]
print(self.dist)
def generate_song(self, size=25):
seed = random.randint(0, self.word_size-3)
seed_word, next_word = self.words[seed], self.words[seed+1]
w1, w2 = seed_word, next_word
gen_words = []
for i in xrange(size):
gen_words.append(w1)
w1, w2 = w2, random.choice(self.dist[(w1, w2)])
gen_words.append(w2)
return ' '.join(gen_words)
if(__name__ == "__main__"):
lyrics_file = open("lyrics.txt","r")
markov = Markov(lyrics_file)
print(markov.generate_song())
# purposefully uncommented so you're obliged to read my blog post. :)
# https://authomaton.blogspot.co.uk/2017/10/machine-learning-but-funner-01-rap-bot.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment