疯狂填词

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

结果应该打印到屏幕上,并保存为一个新的文本文件。

代码:

import re

file = open('before.txt', 'r')
data = file.read()
file.close()
wordList = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
moString = '|'.join(wordList)
mo = re.compile(moString)
result = mo.search(data)
while result != None:
	change = result.group()
	answer = input(f"Enter an {change.lower()}:\n")
	data = mo.sub(str(answer), data, 1)
	result = mo.search(data)

file = open('after.txt', 'w')
file.write(data)
file.close()

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值