Python programming Quick Start Chapter 1 practical project reference answers, python Quick Start
Chapter 4 crazy lyrics for practice projects
Create a crazy lyrics (Mad Libs). The program reads data into a text file and allows users to see ADJECTIVE, NOUN, VERB, and other words in the text file, add their own text.
Start with a text file a.txt
The program code is as follows:
#! /Usr/bin/env python3.4 # coding: UTF-8 # 8.9.2import ref1 = open('a.txt ', 'R') strf1 = f1.read () print ("original file content :") print (strf1) strf1_list = strf1.split ('') f1.close () # Because the words to be replaced in the original file are uppercase English words # use regular expressions to find all replist = re. findall (R' [A-Z] {2,} ', strf1) print ("the word to be replaced in the original file is:") print (replist) print () for rep in replist: inputstr = input ("Enter % s" % rep) print (inputstr) # First insert the replaced word to the position corresponding to the original list strf1_list.insert (strf1_list.index (rep), inputstr) # Then delete the original word strf1_list.remove (rep) # convert the list to the string newstr = ''. join (strfshortlist) print ("the content after replacement is:") # print (newstr) # write a new character string to B .txt and print it to the screen f2 = open(' B .txt ', 'W + ') f2.write (newstr) f2.close () f3 = open(' B .txt ', 'R') print (f3.read () f3.close ()
Output result:
Catb. B .txt
OK.