Python编程快速上手 实践项目8.9.2

来源:互联网 发布:php递归99乘法表 编辑:程序博客网 时间:2024/06/06 03:14

8.9.2 疯狂填词

创建一个疯狂填词(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.
结果应该打印到屏幕上, 并保存为一个新的文本文件。


中间过程

用spilt()方法处理不了标点,考虑用正则表达式直接搜索出需要替换的关键字,然后用re.sub()的方法替换。
原文中出现了两次“NOUN”,用sub方法替换的时候,会将两个地方一起替换了,后面查阅了文档才知道sub方法最后可以加一个count参数可以控制每次替换的个数。


最终实现

import re#读取文本file = open('test.txt', 'r')words = file.read()file.close()#查找关键字pattern = re.compile('ADJECTIVE|NOUN|VERB|ADVERB')mo = pattern.findall(words)#依次替换每一个关键字for word in mo:    repl = input(f'Enter a {word}:\n> ')    regex = re.compile(word)    words = regex.sub(repl, words, 1)print(words)#替换后的文本写入新的文件new_file = open('test2.txt', 'w')new_file.write(words)new_file.close()
原创粉丝点击