Poetry generators: Difference between revisions
(Created page with "Prototyping exercise For: May 17, 2011 == Core == use: strings<br /> split, for, len, strings and the [] syntax Create a poetry generator that filters a text to show only the...") |
No edit summary |
||
(2 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
Prototyping exercise | Prototyping exercise | ||
[[Category: Prototyping]] | |||
For: May 17, 2011 | For: May 17, 2011 | ||
Line 46: | Line 47: | ||
nextwords = {} | nextwords = {} | ||
</source> | </source> | ||
<source lang="python"> | |||
## CODE TO READ A TEXT INTO THE DICTIONARY | ## CODE TO READ A TEXT INTO THE DICTIONARY | ||
## | ## | ||
## Sample Text: "He saw the cat before he saw the potato." | ## Sample Text: "He saw the cat before he saw the potato." | ||
> nextwords['the'] | > nextwords['the'] | ||
['cat', 'potato'] | ['cat', 'potato'] |
Latest revision as of 10:48, 16 May 2011
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']