时间:2020-08-12 python教程 查看: 1018
本文实例讲述了Python疯狂填词程序实现方法。分享给大家供大家参考,具体如下:
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
import re
def madLibs(longStr):
madLibsRex = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB') #正则表达式对象
print(madLibsRex.findall(longStr)) #验证是否模式匹配正确
return madLibsRex.findall(longStr)
openFile = open('123.txt','r')
longStr = openFile.read() #将文本内容读入变量longStr
print("源文本如下:",longStr)
for i in madLibs(longStr): #循环遍历函数返回的匹配对象列表
print("Enter an {0}:".format(i))
longStr = longStr.replace(i,input()) #调用字符串的replace()方法输入替换,再赋值给longStr
print(longStr)
resultFile = open('new123.txt','w') #在当前工作目录创建一个新的文件
resultFile.write(longStr) #将字符串变量写入resultFile对象
openFile.close()
resultFile.close()
希望本文所述对大家Python程序设计有所帮助。