Lecture 33: MadLibs!

posted Mar 21, 2013, 8:40 PM by Samuel Konstantinovich   [ updated Mar 22, 2013, 7:13 AM ]
Your goal over break is to write a simple MadLibs function (due Friday after break)

1. Take any normal text such as Hamlet's soliloquy:

text ='''To be, or not to be--that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep--
No more--and by a sleep to say we end
The heartache, and the thousand natural shocks
That flesh is heir to. '''

2. Modify the text with special all capital letters words to represent NOUN, VERB, ADJECTIVE, etc...
text ='''To VERB, or not to VERB--that is the NOUN:
Whether 'tis nobler in the NOUN to VERB
The NOUNs and NOUNs of ADJECTIVE fortune
Or to take NOUNs against a sea of NOUNs
And by opposing end them. To VERB, to VERB--
No more--and by a VERB to say we end
The heartache, and the thousand ADJECTIVE VERB
That flesh is heir to. '''

3a. Now make a list of nouns, verbs, and adjectives: (The longer the better)

nouns=['fish','computer','Iphone','jaguar','mapo tofu']

3b. It is helpful to write a function that takes a list as a parameter, and returns a random element of the list:
getRandom(nouns) --> 'fish'
getRandom(nouns) --> 'jig'

4a. Write a python program
madlibs(storyString, nounList, verbList, adjectiveList)   
#optionally include other things such as: nameList, adverbList, etc.

This should return a new string with each "NOUN" string replaced with a randomly chosen word from the nounList, each "VERB" replaced with a randomly chosen verb from the verbList, etc.

Example: (underlinded and bolded for clarity)

x="Whether 'tis nobler in the NOUN to VERB The NOUNs and NOUNs of ADJECTIVE fortune"

madlibs(x,nouns,verbs,adjectives)  -->  "Whether 'tis nobler in the jaguar to spin The computers and fishs of silent fortune"  (one of many possible returned values)
#notice 'NOUNs' replaces just the NOUN and keeps 's' right after it. This doesn't work for all nouns, fish for example is not pluralized with an s. Do not worry about this for now, If you want to handle special cases later, you can improve your basic madlibs function 

This requires you to find ALL instances of "NOUN" and replace each one with a word chosen from a list. 

#CHALLENGE: optionally keep track of words that are supposed to be the same
"to be or not to be" has the verb 'be' twice.

"to VERB1 or not to VERB1"  is a way you can keep track of specific words that should match. 

"Bob works fast. Bob also sings hard. Dave works with bob"
can be changed to 
"NAME1 VERB1s fast. NAME1 also VERBs  hard. NAME2 with NAME1"
you can add a 1 or 2 digit number and keep track of the numbered words in your program as you do replacement. You can make the number optional or required.