Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mad Libs Program
#10
I've updated my code here using the substitution/json method.

import json, os,random
#Change the working directory to the Mad Libs base folder.
os.chdir('/mydirectory')
#randomly Select a Story to be opened from the File
story = open(random.choice(os.listdir('/mydirectory')))
storyContent = story.read()
#Load in the substitutions found in the story
madlib = json.loads('''
{
    "substitutions": [
        {
            "key": "NOUN1",
            "type": "Noun"
        },
        {
            "key": "ADJECTIVE1",
            "type": "Adjective"
        },
        {
            "key": "ADJECTIVE2",
            "type": "Adjective"
        },
        {
            "key": "VERB1",
            "type": "Verb"
        },
        {
            "key": "BODY PART1",
            "type": "Body Part"
        },
        {
            "key": "BODY PART2",
            "type": "Body Part"
        }
    ]
}
''')
substitutions_to_do = {}
for substitution in madlib["substitutions"]:
    choice = input("Please provide a {}: ".format(substitution["type"]))
    substitutions_to_do[substitution["key"]] = choice
print(storyContent.format(**substitutions_to_do))
This does work for this story. Where it doesn't work is if I have a completely different story with different phrases/parts of speech required. I would like to program to step through a story and find all the keys and types, without me having to hard code it in. That will allow for new keys to be added in new stories. Is it possible to do this with json?
Reply


Messages In This Thread
Mad Libs Program - by theguywithcurls - Nov-13-2019, 04:41 PM
RE: Mad Libs Program - by micseydel - Nov-14-2019, 12:04 AM
RE: Mad Libs Program - by jefsummers - Nov-14-2019, 02:31 AM
RE: Mad Libs Program - by micseydel - Nov-14-2019, 05:10 PM
RE: Mad Libs Program - by theguywithcurls - Nov-15-2019, 04:20 AM
RE: Mad Libs Program - by jefsummers - Nov-15-2019, 12:37 PM
RE: Mad Libs Program - by micseydel - Nov-15-2019, 09:26 PM
RE: Mad Libs Program - by theguywithcurls - Nov-15-2019, 11:43 PM
RE: Mad Libs Program - by micseydel - Nov-16-2019, 12:07 AM
RE: Mad Libs Program - by theguywithcurls - Nov-16-2019, 07:38 PM
RE: Mad Libs Program - by theguywithcurls - Nov-17-2019, 12:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Running 3rd party libs on Steam Deck (Arch Linux) with restricted access metulburr 0 3,357 Jan-07-2023, 10:41 PM
Last Post: metulburr
  How can I use CRC libs in python? blodht 0 2,707 Feb-03-2020, 10:26 PM
Last Post: blodht
  using py32, just need py64 LIBS for now, how to install? davecotter 1 2,843 Jan-29-2019, 10:40 PM
Last Post: davecotter
  [split] adding 3rd party libs Blue Dog 7 8,439 Oct-22-2016, 12:03 PM
Last Post: Blue Dog

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020