Last active
July 6, 2017 22:26
-
-
Save hanskamin/17ac667722ededb0ff45133a725cfc3f to your computer and use it in GitHub Desktop.
Using Our Markov Chain to Predict New Lyrics
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
# coding: utf-8 | |
# Hans Kamin | |
# Spring 2017 | |
# Predicting Lyrics From Our Chain | |
import random | |
def generate_new_lyrics(chain): | |
""" | |
Args: | |
- chain: a dict representing the Markov chain, | |
such as one generated by generate_new_lyrics() | |
Returns: | |
A string representing the randomly generated song. | |
""" | |
# a list for storing the generated words | |
words = [] | |
# generate the first word | |
word = random.choice(chain[(None, "<START>")]) | |
words.append(word) | |
# Begin with the first bigram in our chain. | |
last_2 = (None, "<START>") | |
while words[-1] != "<END>": | |
# Generate the next word. | |
word = random.choice(chain[last_2]) | |
words.append(word) | |
# Shift the current bigram to account for the newly added word. | |
last_2 = (last_2[1], words[-1]) | |
# Join the words together into a string with line breaks. | |
lyrics = " ".join(words[:-1]) | |
return "\n".join(lyrics.split("<N>")) | |
print(generate_new_lyrics(chain)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment