79485835

Date: 2025-03-05 08:28:06
Score: 2
Natty:
Report link

I'm very new to Python, and I'm working on Automate the Boring Stuff with Python (2nd edition). I used a while loop to replace the keywords one by one using re.search, and I also used a dictionary to get the phrasing for the input questions correct ('Enter an adjective', 'Enter a noun' etc.).

I'm not very familiar with format strings yet, but if there's an easier and more convenient way of doing this then I'd appreciate any tips or comments.

#! python3
# madLibs.py - Reads text files and replaces ADJECTIVE, NOUN, ADVERB and VERB words with input from user.

from pathlib import Path
import re

# Put the correct phrasing for each replacement word in a dictionary:
inputStr = {'ADJECTIVE': 'an adjective', 'NOUN': 'a noun', 'ADVERB': 'an adverb', 'VERB': 'a verb'}

filePath = input('Input relative path and name of text file: ')
madLib = Path(filePath).read_text()

regex = r'ADJECTIVE|NOUN|ADVERB|VERB'

while True:
    mo = re.search(regex, madLib)
    if mo == None:
        break
    else:
        userInput = input('Enter ' + inputStr.get(mo.group()) + ':\n') # Ask for input based on keyword found by search
        madLib = re.sub(regex, userInput, madLib, count=1) # Replaces one instance of the keyword found with userInput

print(madLib)
outputFile = open(f'new{filePath}', 'w')
outputFile.write(madLib)
outputFile.close()
Reasons:
  • Blacklisted phrase (1): any tips
  • RegEx Blacklisted phrase (1.5): I'm very new
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: bergand