Create a crazy lyrics (Mad Libs) program that will read into the text file and let the user in the text
where adjective, NOUN, adverb, or verb are present in the file, plus their own
your own text. For example, a text file might look like this:
The adjective panda walked to the NOUN and then VERB. A nearby NOUN was
Unaffected by these events.
The program will find these occurrences of the words 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 files will be created:
The silly panda walked to the chandelier and then screamed. A nearby Pickup
Truck was unaffected by these events.
Source:
1 #Coding=utf-82 ImportRe3 #Open File4Wfile = open ('Sentence.txt','R')5Words =Wfile.read ()6 wfile.close ()7 Print(words)8 #Regular reads the word and replaces the word in turn9Wregex = Re.compile (r'\w[a-z]+')Ten forContentinchWregex.findall (words): Onereplacecontent= input ('Enter a%s:\n'%content) A #Print (content) - #print (replacecontent) -Regex = re.compile (content)#matches the matched word to a regular lookup rule, and then the word lookup replaces it with the input content . theWords=regex.sub (replacecontent,words,1)#the replaced content continues to be saved in the original file read content, otherwise the replacement content will not be saved, the Sub function added quantity is because there are two noun, will be replaced at the same time, so set to replace only one - Print(words) - #new content is written to a new file -Nwfile= Open ('Sentence1.txt','W') + Nwfile.write (words) -Nwfile.close ()
python-Regular and file items (crazy lyrics)