Madlib Generator In Python In Just 4 Steps

Madlib, if you don’t know, is a fun game. Here, the user is asked for various words. Then, the user’s words, are embedded in a story to make it sound hilarious.

We are going to make this up today.


Idea

For this, we first need some stories with placeholders. Then we simply need to input words wherever the placeholders occur. Finally, we can replace the placeholders with the input words. And our Madlib is ready.

Approach

We can divide this task into 4 simple steps:

  1. Get the stories from the file.
  2. Separate these stories (list of stories(str)) and select one out of them(one string).
  3. Now convert this story(string) to a list of words.
  4. Iterate through the list of words. Wherever placeholder is found ask for input or allow generating a random word.

Implementation

You can use this text file:


Step 1: Extracting story from the file

Now let’s get the stories from this file:

# Step 1: get data from file
with open('Python-projects\\madlib generator\\madlib_templates.txt') as f:
    stories = f.read()
    print(stories)

All the stories will be printed.

Step 2: Separating the stories

If you have seen the file you’ll notice that the first line has the title of the story, the second has the story, the third leaves a blank space, and then again comes the title of the next story.

extracting story for madlibextracting story for madlib

We just need the story. So, we will start with 1, to skip blank and the next story’s title we will provide step = 3:

# Step 2: separate stories
list_stories = stories.split('\n')[1::3]
print(len(list_stories))
print(list_stories)

Step 3: Getting a story and other requirements

In order to provide random words we need to have them stored somewhere:

# create a dictionary of random words
random_words = {
            '<noun>':['cat', 'mountain', 'bicycle', 'library', 'ocean', 'pizza'],
            '<adjective>':['Sparkling', 'Mysterious', 'Playful', 'Enchanting', 'Courageous', 'Lively'],
            '<verb>': ['jump', 'laugh', 'run', 'dance', 'explore', 'cook'],
            '<emotion>':['joyful', 'melancholic', 'excited', 'content', 'anxious', 'grateful'],
            '<place>':['paris', 'tokyo', 'sydney', 'venice', 'brazil', 'park']
        }

Now let’s select a story and a list of words that will act as placeholders:

import random
possible_blanks = ['<adjective>', '<noun>', '<verb>', '<emotion>', '<place>'] # placeholders
selected_story = random.choice(list_stories)
selected_story = selected_story.split(' ') # converting the string to list of words.

Step 4: Generating the Madlib

Now, we will iterate through each word in the story. If the word is a placeholder then we will ask for user input. If the user enters r we will generate a random word. Then, we will update the respective placeholder in the list.

Finally, we will print the story after converting it to a string.

for word in selected_story:
    if word in possible_blanks:
        get_word = input(f"Enter a {word} (or type r for random word): ").lower()

        if get_word == 'r':
            get_word = random.choice(random_words[word])
        # Replacing the placeholder with random/user input word
        selected_story[selected_story.index(word)] = get_word
        # selected_story.index(word): gets index of the placeholder.
        # This index is then updated with selected_story[index] = get_word
# Printing the generated story        
print(' '.join(selected_story))

And that’s it. We have our Madlib generator ready.

Challenge Feature 🧗‍♀️

Your challenge is to display the title before the Madlib displays.

Leave a Reply

This Post Has One Comment

  1. gold

    Thank you for the good writeup. It in fact was a amusement
    account it. Glance advanced to more added agreeable from you!

    However, how can we keep up a correspondence?