Python-正则与文件项目(疯狂填词)

创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本
文件中出现ADJECTIVE、NOUN、ADVERB 或VERB 等单词的地方,加上他们自
己的文本。例如,一个文本文件可能看起来像这样:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
程序将找到这些出现的单词,并提示用户取代它们。
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
以下的文本文件将被创建:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.

源码:

 1 # coding=utf-8
 2 import re
 3 # 打开文件
 4 wfile = open('sentence.txt','r')
 5 words = wfile.read()
 6 wfile.close()
 7 print(words)
 8 #正则读取单词并依次替换单词
 9 wRegex = re.compile(r'\w[A-Z]+')
10 for content in wRegex.findall(words):
11     replaceContent= input('Enter a %s:\n'%content)
12     #print(content)
13     #print(replaceContent)
14     regex = re.compile(content)   #将匹配出的单词作为正则查找规则,再词查找并用输入的内容替换
15     words=regex.sub(replaceContent,words,1)  # 替换的内容继续保存在原来文件读取的内容中,不然替换的内容不会被保存,sub函数添加数量是因为有两个NOUN,会把同时替换,所以设置一次只替换一个
16 print(words)
17 #新内容写入新文件
18 nwfile= open('sentence1.txt','w')
19 nwfile.write(words)
20 nwfile.close()

猜你喜欢

转载自www.cnblogs.com/Annaying/p/9142318.html