思路:
- 读文件
- 加工内容(替换字符串)
- 写文件
注意点:
- replace(旧串,新串,匹配次数) 第3个参数可以限定匹配最多的次数,可参考 https://www.runoob.com/python/att-string-replace.html
- 读取、写入都要关闭对应文件
# P156 8.9.2 疯狂填词
import os.path
def vreplace(inFile):
inFile1=open(inFile)
inContent=inFile1.read()
toReplace=['ADJECTIVE','NOUN','VERB','NOUN']
for i in range(len(toReplace)):
if toReplace[i][0].lower() in ['a','e','i','o','u']: # 对元音字母做判断,输出提数有差异
print('Enter an '+toReplace[i]+' :')
else:
print('Enter a '+toReplace[i]+' :')
userIn=input() # 获取输入
inContent=inContent.replace(toReplace[i],userIn,1) # replace() 第3个参数可以限定匹配最多的次数,可参考 https://www.runoob.com/python/att-string-replace.html
inFile1.close() # 关闭文件,PS:读取、写入都要关闭对应文件
outFile=open('out.txt','w')
outFile.write(inContent)
outFile.close()
outUrl=os.getcwd() # 获取文件地址
strR='新文件已生成,请查看('+outUrl+'\out.txt)' # 提示新文件路径
return(strR)
strReturn=vreplace('in.txt')
print(strReturn)
运行结果是这样:
产出的新文件out.txt
产出新文件的内容: