import os
import re
filename = input('输入要处理的文件名:')
while filename != ' ' and os.path.isfile(filename) != True:
filename = input('文件不存在,请重新输入:')
file = open(filename)
words = file.read()
file.close()
pattern = re.compile('ADJECTIVE|NOUN|VERB|ADVERB')
mo = pattern.findall(words)
for word in mo:
repl = input(f'Enter a {word}:\n> ')
regex = re.compile(word)
words = regex.sub(repl, words, 1)
print(words)
print('新文件为:madLibs_replace.txt')
newFile = open('madLibs_replace.txt', 'w')
newFile.write(words)
newFile.close()
madLibs.txt
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.