python-Regular and file items (crazy lyrics)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.