The project outline:
Create a Mad Libs program that reads in text files 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 file 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 solution:
import pyinputplus as pyip
import re
text_file = open("mad_libs_text.txt", "r")
text = text_file.read()
reg_obj = re.compile(r"ADJECTIVE|NOUN|VERB")
mo = reg_obj.findall(text)
new_text = text
for i in mo:
art = "a"
if i == "ADJECTIVE":
art = "an"
user_inp = pyip.inputStr(f"Enter {art} {i.lower()}\n")
new_text = re.sub(i, user_inp, new_text, count=1)
print(new_text)
new_text_file = open("mad_libs_new.txt", "w")
new_text_file.write(new_text)
text_file.close()
new_text_file.close()
Thanks in advance for the critique.
i
is a bad name. Spell outarticle
. use a ternary operator too. Instead oftext
andnew_text
, I would haveoriginal_text
andtext
and modifytext
. for bothopen
calls put them in a context manager instead of calling.close()
. You could speed up by calling insteadreg_obj.find(text[last_found:])
. Your code looks great without changes, but I think my suggestions would improve it. Keep up the good work. \$\endgroup\$