I am a beginner with only about 2 months under my belt. I'm learning Python 3 using the Automate the Boring Stuff with Python manual. In the chapter on reading and writing files one of the exercises is to make a program that would fill in a mad lib that was read from a file. It works, but it's not very elegant. Can anyone offer me advice on how to better do this task or a better direction to go?
# madLibs.py
import re, os
# define regex
verbRegex = re.compile(r'verb', re.I)
nounRegex = re.compile(r'noun', re.I)
adjectiveRegex = re.compile(r'adjective', re.I)
# change directory
os.chdir('C:\\MyPythonScripts')
# read contents of madLib.txt and store it in variable madLib
madLibFileObject = open('madLib.txt')
madLib = madLibFileObject.read()
y = 0
newMadLib = []
for word in madLib.split():
newMadLib.append(word)
if verbRegex.search(word) != None:
x = input('Enter VERB: ')
newMadLib[y] = x
elif nounRegex.search(word) != None:
x = input('Enter NOUN: ')
newMadLib[y] = x
elif adjectiveRegex.search(word) != None:
x = input('Enter ADJECTIVE: ')
newMadLib[y] = x
y += 1
newMadLib = (' ').join(newMadLib)
print(madLib)
print (newMadLib)