I am currently working through "Automate the boring stuff with python". I am on the practice project for chapter 8 titled "Mad Libs". The task is as follows:
Create a Mad Libs program that reads in text fles and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text fle may look like this:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.The program would find these occurrences and prompt the user to replace them.
Enter an adjective: silly
Enter a noun: chandelier
Enter a verb: screamed
Enter a noun: pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.The results should be printed to the screen and saved to a new text file.
My current program is as follows:
#! python3
# Requests user for an ADJECTIVE, NOUN, ADVERB, and a NOUN
# Replaces the words ADJECTIVE/NOUN/ADVERB/NOUN with the input in a txt file
# Saves the new Mad Lib as a new txt file
import re
reADJECTIVE = re.compile(r'''(ADJECTIVE)''')
reNOUN = re.compile(r'''(NOUN)''')
reVERB = re.compile(r'''(VERB)''')
for i in range(1):
# Gets user input for ADVECTIVE/NOUN/VERB/NOUN
ADJECTIVE = input('Enter an adjective: ')
NOUN = input('Enter a noun: ')
VERB = input('Enter a verb: ')
NOUN2 = input('Enter a noun: ')
madLibFile = open('madlib%s.txt' % (i + 1))
madLibFileContent = madLibFile.read()
madLibFile.close()
madLibFileContent = madLibFileContent.split('. ')
print(madLibFileContent)
newMadLib = re.sub(reADJECTIVE, ADJECTIVE, madLibFileContent[0])
newMadLib = re.sub(reNOUN, NOUN, newMadLib)
newMadLib = re.sub(reVERB, VERB, newMadLib)
newMadLib = newMadLib + '. ' + re.sub(reNOUN, NOUN2, madLibFileContent[1])
print(newMadLib)
For the given example this program works, however due to the way i seperate the file it reads in by the fullstop/period it only works when the format of the input file is:
ADJECTIVE NOUN ADVERB. NOUN.
and would not work for any other format such as:
ADJECTIVE NOUN. ADVERB NOUN.
My initial idea was to use the regex pattern:
(ADJECTIVE).*(NOUN).*(VERB).*(NOUN)
This works if we assume any given Mad Lib follows the same pattern of Adjective-Noun-Verb-Noun.
If I were to use:
re.sub(r'(NOUN)', replacement, someString)
It would replace ever instance of NOUN in the string with replacement. Is it possible to replace each capture group with something different?
Thank you for your time, and I hope the question was clear enough :)