Nov-16-2019, 07:38 PM
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?