This time at Learn Something we decided to try a classic game: Madlibs! The challenge was to make a program that will read in a Madlib template from a user. It will then ask for the appropriate parts of speech for the user to fill in to complete the Madlib. Finally, it will fill in all the blanks in the Madlib with the user’s words and display the result to the user.
We decided our token in the Madlib template would be like {{noun}} with the appropriate part of speech between the curly braces. With that in mind, our template looks like this:
Learn Something is {{adj}}. I learned a lot about {{noun}} and {{noun}} this time. It is my favorite thing to {{verb}} every month. {{name}} and {{name}} are the coolest guys who work at Fanzoo Technology. They are really {{adj}} when they {{verb}} my {{noun}}.
We decided to try our solution in Python this month. Our code is as follows:
import re f = open('madlib_template.txt', 'r') final_madlib = [] for word in f.read().split(): if "{{" in word: whole_token = re.search('({{.+?}})', word).group(1) token_word = re.search('{{(.+?)}}', word).group(1) user_word = raw_input("give me a(n) " + token_word + ": ") final_madlib.append(word.replace(whole_token, user_word)) else: final_madlib.append(word) print " ".join(final_madlib)
First, we import a regular expression library for finding our tokens, then we open our file (which we saved as “madlib_template.txt”) in read mode. On line 5 we instantiate an empty list for building the final story we will display to the user.
We cycle through all the words in the template. If the word contains the start of a token ( {{ ), we get the entire token including the brackets (line 9), and the token word, which excludes the brackets (line 10). We then get input from the user (line 11), replace the entire token including the brackets with the user’s word, and add the result to the final_madlib list we made earlier. If we find that the word we are working with doesn’t contain a token at all, we simply skip the middle steps and add it straight to the final_madlib list.
Finally, we cycle through all the words and print our list to the screen. The result reads like a story with all of the tokens filled in with the user’s words!
If you’d like to try this yourself, simply copy and paste our template and code into some files and run them using your command prompt. You can create your own templates and have your friends fill them out when they run the program.
Leave a Reply