python 疯狂填词 mad libs

import os
import re
# 读取文本文件
file = open(r'F:\workspace\python\text\madlib.txt')
strs = file.read()
#sub函数不改变原字符串
adjective = input("Enter a adjective:")
adjective_regex = re.compile('ADJECTIVE')
strs = adjective_regex.sub(adjective, strs)

noun = input("Enter a noun:")
noun_regex = re.compile('NOUN')
strs = noun_regex.sub(noun, strs)

verb = input("Enter a verb:")
verb_regex = re.compile('VERB')
strs = verb_regex.sub(verb, strs)

noun = input("Enter a noun:")
noun_regex = re.compile('NOUN')
strs = noun_regex.sub(noun, strs)

print(strs)
# 写入改动后的文件
fileObj = open(r'F:\workspace\python\text\madlib_change.txt', 'w')
fileObj.write(strs)
fileObj.close()

madlib.txt内容:The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events

你可能感兴趣的:(python)