Poetry generators

From XPUB & Lens-Based wiki

Prototyping exercise

For: May 17, 2011

Core

use: strings
split, for, len, strings and the [] syntax

Create a poetry generator that filters a text to show only the first letters of each words but for the rest preserving the layout (ie use spaces instead of the original characters).

A loop like the following may be helpful to start:

f = open("myfile.txt")
for line in f:
    for word in line.split():
        print word

Remember, if you are using non-ASCII characters to use codecs.open:

import codecs
f = codecs.open("myfile.txt", encoding="utf-8")

some other code to try:

print word,
print len(word)
print word[1]


Advanced

Create a poetry generator that implements a simple "markov chain" (ie a text can be read, and then new texts generated by making random choices of words known to follow a given word.)

use: strings, lists, dictionaries

(Hint: Remember that while a dictionary is (typically) indexed by words, the associated value can be any kind of Python object. Use a single dictionary to store the "next words" of a given word (ie a dictionary that maps a word to a list of next words, ie:

nextwords = {}
## CODE TO READ A TEXT INTO THE DICTIONARY
##
## Sample Text: "He saw the cat before he saw the potato."
> nextwords['the']
['cat', 'potato']
> nextwords['he']
['saw', 'saw']
> nextwords['before']
['he']