创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本 文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自 己的文本
import re
with open('F:\TEST_FILE\python编程快速上手\新建文本文档.txt') as file_object:
lines= file_object.readline()
words=['ADJECTIVE','NOUN','ADVERB','VERB']
#方法1:
for word in words:
text_replace=input('Enter a '+word.lower()+':')
lines=lines.replace(word,text_replace)
print(lines)
#方法2:
for word in words:
wordRegex=re.compile(word)
text_replace=input('Enter a '+word.lower()+':')
lines=wordRegex.sub(text_replace,lines)
print(lines)
输出效果: