A note on resources: This tutorial was created on Mac OS X Version 10.9.5. I used the default pre-installed version of Python, version 2.7.5. I used Apple’s pre-installed Terminal application and Bare Bones Software’s free TextWrangler download.
- Open TextWrangler
- Enter # -*- coding: utf-8 -*- to allow for unicode characters. I had trouble with question marks and semicolons causing errors when running my code; this discussion seemed to fix the problem.
- Determine which parts of speech you will be replacing in your text for the Mad Lib. Start simple; for this tutorial, I replaced singular nouns, present tense verbs, adjectives, and adverbs.
- Define the part of speech
- Type the part of speech label
- Type = to indicate the words it will represent
- Type your values between brackets [ ]
- Each value should be enclosed by quotation marks ” “
- Separate each value by a comma outside of the quotation marks “,
- Repeat for each part of speech you are defining; each list should be on a different line (example below)
- Type import random on a new line to import the module that will allow for you to randomize your text
- Paste your text on a new line and format. You can use any text, or create your own!
- Type print in front of your text
- Ensure the text is between quotation marks – this will ensure it appears as-is when the code is run
- Consider separating your text into multiple lines, if it is not already, in order to make the code readable
- Edit your text to suit the code. Ensure that \ are properly added to words with apostrophes or quotation marks that you would like to print when the code is run. Ensure all apostrophes/quotations are opened and closed properly. Ensure each line has “print” in front of it.
- Replace the words with the name of the part of speech in all caps and exclude them from the parentheses enclosing the string. This is so you can easily identify where you will paste the code for the random text generator.
- You can take this opportunity to paste in the random.choice code from step 7a, however I suggest waiting so that you can easily review the words that you removed.
- Ensure that the words you are replacing match the tense; for example, do not replace a plural noun if the words in your noun list are singular.
- Enter the randomization code into your text
- Run your code through Terminal by opening the directory where your TextWrangler file is saved typing python filename.py
Here is what the code looks like in its entirety:
Here are a few examples of the results: