17 Mad Libs: Using regular expressions

 

When I was a wee lad, we used to play at Mad Libs for hours and hours. This was before computers, mind you, before televisions or radio or even paper! No, scratch that, we had paper. Anyway, point is we only had Mad Libs to play, and we loved it! And now you must play!

We’ll write a program called mad.py that will read a file given as a positional argument and find all the placeholders noted in angle brackets like <verb> or <adjective>. For each placeholder, we’ll prompt the user for the part of speech being requested like "Give me a verb" and "Give me an adjective." (Notice that you’ll need to use the correct article just as in "Crow’s Nest.") Each value from the user will then replace the placeholder in the text, so if the user says "drive" for "verb," then <verb> in the text will be replace with drive. When all the placeholders have been replaced with inputs from the user, print out the new text.

There is a 17_mad_libs/inputs directory with some sample files you can use, but I encourage you to create your own. For instance, here is a version of the "fox" text:

$ cat inputs/fox.txt
The quick <adjective> <noun> jumps <preposition> the lazy <noun>.

When the program is run with this file as the input, it will ask for each of the placeholders and then print the silliness:

$ ./mad.py inputs/fox.txt
Give me an adjective: surly
Give me a noun: car
Give me a preposition: under
Give me a noun: bicycle
The quick surly car jumps under the lazy bicycle.

17.1  Writing mad.py

 
 

17.1.1  Using regular expressions to find the pointy bits

 
 

17.1.2  Halting and printing errors

 
 

17.1.3  Getting the values

 
 
 

17.1.4  Substituting the text

 

17.2  Solution

 
 
 
 

17.3  Discussion

 

17.3.1  Defining the arguments

 
 
 

17.3.2  Substituting with regular expressions

 
 
 

17.3.3  Finding the placeholders without regular expressions

 
 
 
 

17.4  Review

 
 

17.5  Going Further

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest