题目:
创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自己的文本。结果应该打印到屏幕上,并保存为一个新的文本文件。
代码:
#! python3
# MadLibs.py - replace "ADJECTIVE"\"NOUN"\"ADVERB"\"VERB" in a file with the words users enter
# Usage:
# python MadLibs.py file.txt - Prcesses the file.txt
# python MadLibs.py - pirnts the Usage on the screen
import re,sys,os
replacedWords=["ADJECTIVE","NOUN","ADVERB","VERB"]
# 命令行输入参数为空,print the Usage
if len(sys.argv)==1:
print('''
please enter the filename
# MadLibs.py - replace "ADJECTIVE"\"NOUN"\"ADVERB"\"VERB" with the words users enter in a file
# Usage:
# python MadLibs.py file.txt - Prcesses the file.txt''')
# 读取文件内容,替换字符串
elif len(sys.argv)==2:
# 判断文件是否存在
if os.path.exists(sys.argv[1])==False:
print(sys.argv[1]+' does not exist!')
else:
with open(str(sys.argv[1]),'r+') as file:
text=str(file.read())
# 提醒用户输入待替换的字符串
for replacedWord in replacedWords:
newWord=input("Enter an %s:\n"%replacedWord)
# 写正则表达式,并替换
Regex=re.compile(replacedWord)
text=Regex.sub(newWord, text)
print(text)
# T将替换后的字符串写入文件,并关闭文件
with open('newFile.txt','w') as file:
file.write(text)