码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-06-05 23:13:20      阅读:582      评论:0      收藏:0      [点我收藏+]

标签:style   span   IV   regex   cti   input   NPU   eve   utf-8   

创建一个疯狂填词(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()

 

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

标签:style   span   IV   regex   cti   input   NPU   eve   utf-8   

原文地址:https://www.cnblogs.com/Annaying/p/9142318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!