【发布时间】:2019-10-09 09:57:41
【问题描述】:
你好,这个练习说: 创建一个 Mad Libs 程序,该程序读取文本文件并允许用户在文本文件中出现单词 ADJECTIVE、NOUN、ADVERB 或 VERB 的任何位置添加自己的文本。
textfile = 形容词 panda 走到名词和动词。附近的一个名词是 不受这些事件的影响。
到目前为止我所拥有的是:
import re
#filename = input('Input the Filename: ')
with open('madlibs.txt') as file:
content = file.read()
file.close()
regex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
#regex = re.compile('[A-Z]{3,}')
matches = regex.findall(content)
#newWord = []
for word in matches:
user_input = input('Enter %s: ' % word)
# newWord.append(user_input)
new_content = content.replace(word,user_input,1)
print(new_content)
我的输入是:
Enter ADJECTIVE: heavy
Enter NOUN: whale
Enter VERB: runs
Enter NOUN: door
我的输出:
The ADJECTIVE panda walked to the door and then VERB. A nearby door was
unnafected by these events.
有人可以向我解释我做错了什么吗?由于某种原因,我似乎无法更改 ADJECTIVE 和 VERB,我还尝试了大写的注释正则表达式,它也是如此,所以问题出在其他地方。
【问题讨论】:
-
我还必须将 content.replace(word,user_input) 替换为 content.replace(word,user_input,1) 以便正确替换名词
标签: python