For this assignment we will use Python 3's open()
and readline()
functions to read in a blank MadLib. Then we will use the input()
function to ask the user for words from a particular part of speech (e.g. noun, adjective, verb, etc). Finally we'll use Python's replace()
function to replace the blanks with user input. You may find the website How to create a Mad Libs game in Python and slides ~168 - ~179 of the Computer Programming B slide presentation helpful.
- Your Mad Libs program must use at least two files: A Python file with the program code and a seperate text file with a blank mad lib.
- Your blank Mad Lib must be at least 5 lines long and have 3 or more parts of speech.
- Your program will need a loop to go through the blank Mad Lib one line at a time replacing the blanks
-
For this assignment we will have two files:
- a text (
.txt
) file with the blank Mad Lib - a Python file (
.py
) with the Python code that reads in the blank file and displays the modified version with user input
- a text (
-
Let's start with the text file. Create a text file with your blank Mad Lib. You can use the following Old Macdonald lyrics, Afraid Of The Dark, Spooky Stuff, Talk Like A Pirate or make up your own. (Note that the blanks in the Mad Lib are marked with all caps like
NOUN
)
ADJECTIVE Macdonald had a NOUN, E-I-E-I-O
and on that NOUN he had an ANIMAL, E-I-E-I-O
with a NOISE NOISE here
and a NOISE NOISE there,
here a NOISE, there a NOISE,
everywhere a NOISE NOISE,
ADJECTIVE Macdonald had a NOUN, E-I-E-I-O.
- Give the file a meaningful name like
MadLibs.txt
- Now we'll start writing the Python program
- Add the following code to your Python program (the
.py
file) that opens the text file and assigns it to a variable:
f = open('MadLibs.txt','r')
madlibText = f.readlines()
print(madlibText)
- Run the program. You should see output like:
['ADJECTIVE Macdonald had a NOUN, E-I-E-I-O\n', 'and on that NOUN he had an ANIMAL, E-I-E-I-O\n', 'with a NOISE NOISE here\n', 'and a NOISE NOISE there,\n', 'here a NOISE, there a NOISE,\n', 'everywhere a NOISE NOISE,\n', 'ADJECTIVE Macdonald had a NOUN, E-I-E-I-O.\n', '\n']
madlibText
is a list. Each item in the list is a line from the text file.- Now we need to add code to get user input for each part of speech that is marked in all caps. In the example text there are:
ADJECTIVE
NOUN
ANIMAL
NOISE
- Here's some sample code we could use for user input:
noun = input("Enter a noun: ")
print(noun)
- Now we'll use Python's
replace()
function to replace the blankNOUN
in the first line ofmadlibText
. Change theprint
to
line = madlibText[0].replace("NOUN",noun)
print(line)
- Now create a loop to go through each line in
madlibText
and change every occurance of the blankNoun
- Finally, add more user input for the other parts of speach and replace those as well
This assignment is based on an assignment at Te@ch with ICT