I am working through Automate the Boring Stuff. How can I make this code cleaner/better?#madlibs.py : ABS Chapter 8 Project#Make mad libs using madlibtemplate.txt file that will prompt user for parts of speech#Will return new file with replacements called madlib.txtimport re, os#Create template.txt file if doesn't existprint(Let's play MadLibs! \n Note: Your current working directory is , os.getcwd())if os.path.exists('madlibtemplate.txt') == False:    print(No template file found. Using default 'madlibtemplate.txt')    template = open('madlibtemplate.txt', 'w+')    template.write(The ADJECTIVE girl walked to the NOUN and then VERB.    A nearby NOUN was upset by this.)else:    print(Using your 'madlibtemplate.txt' file:)    template = open('madlibtemplate.txt', 'r')#Extract text from template file & turn into list of wordstemplate.seek(0) #reset pointer to beginning of filetext = (template.read()).lower() #make lowercase to match parts of speechwordregex = re.compile(r'\w+|\s|\S')words = re.findall(wordregex, text)#Find and replace parts of speechfor i, word in enumerate(words):    for part_of_speech in ['adjective', 'noun', 'adverb', 'verb', 'interjection']:        if word == part_of_speech:            print('Enter a(n) %s ' % part_of_speech)            words[i] = input()madlib_text_unformatted = ''.join(words)#Capitalize first letter in each sentence (Function found on stackoverflow)def sentence_case(text):    # Split into sentences. Therefore, find all text that ends    # with punctuation followed by white space or end of string.    sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)    # Capitalize the first letter of each sentence    sentences = [x[0].upper() + x[1:] for x in sentences]    # Combine sentences    return ''.join(sentences)madlib_text = sentence_case(madlib_text_unformatted)#Print result and save to a new fileprint('Here we go... \n')print(madlib_text)madlib = open('madlib.txt', 'w')madlib.write(madlib_text)madlib.close()template.close()print(\n This has been saved to file 'madlib.txt')
Beginner code for MadLibs game
python;beginner;regex