Poetic Formulation with Assistance from Mr. Markov
For this week’s RWET homework, I decided to update my poetic form assignment to include a Markov text generator. This new version of my program feeds a source text through a Markov generator that spits out a new text consisting of “words” derived by predictive analysis, then randomly selects “words” of appropriate length to create a poem. Below is my Python code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #Kim Ash #charlenMarkov.py #feeds text through Markov by char, then uses regex to find words of char lengths 1-9 #creates poem of format 3 5 9 / 2 4 6 / 7 8 import sys import random import re import markov #class definition from Adam Parrish's markov_by_char.py class CharacterMarkovGenerator(markov.MarkovGenerator): def tokenize(self, text): return list(text) def concatenate(self, source): return ''.join(source) #list of 9 empty lists, one for each length words_by_len = [ [], [], [], [], [], [], [], [], [] ] #list for words that will be in poem poem_words = list() #send text through Character Markov Generator generator = CharacterMarkovGenerator(n=4, max=500) for line in sys.stdin: line = line.strip() generator.feed(line) line = generator.generate() for i in range(len(words_by_len)): #find words of each length (i+1 because range() starts at 0) regexp = r"\b\w{" + str(i+1) + r"}\b" for match in re.findall(regexp, line): words_by_len[i].append(match) #randomly select words for use in poem for i in range(len(words_by_len)): poem_words.append(random.choice(words_by_len[i])) print poem_words[2] + " " + poem_words[4] + " " + poem_words[8] print poem_words[1] + " " + poem_words[3] + " " + poem_words[5] print poem_words[6] + " " + poem_words[7] |
I thought it might make a nice comparison with the previous version of this program if I used the same source text, so I made several poems using “Tess of the D’Urbervilles” again (also, I couldn’t resist another opportunity to make a mess of this awful awful book). Below is a poem for n = 2. It looks kind of like Old English:
But seare menindown my cass tholly praccid shervill
By far, my favorite results came from n = 3:
her eccle threached my here invity Queener pictisfy
And since I liked n = 3 so much, here’s another:
tis befor almosphen am call threen Greathe descarts
At n = 4, it starts to look more like English:
and words unlighter to well basked studied dairyman
And n = 5 is just kind of boring:
the happy gentleman we also looked herself followed