我正在使用Python中的“自动化无聊事物”一书来编写MadLib程序。我确定我的程序正在运行,但当用户需要输入输入时,我一直在收到这个奇怪的“NameError”。Python Madlib自动化无聊东西
这是我的代码。我的计划是在看到消息已成功加入后将内容写入文件。
#!/usr/local/bin/python3
import sys
'''
Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file.
'''
breaks = ["noun", "verb", "adverb", "adjective"]
'''Program Usage and Exit Case'''
if len(sys.argv) < 2:
print("Usage: ./mad.py <FileName>")
sys.exit()
'''Read in File and Store Contents in Array'''
file = open(sys.argv[1])
chunk = str(file.read()).split()
****'''Search through text for keywords'''
for word in chunk:
if word.lower() in breaks:
chunk[word] = input("Enter %s: " %word)****
newMessage = " ".join(chunk)
print(newMessage)
file.close()
您确定代码在Python 3中运行?可能发生的事情是它实际上在Python 2中运行,在Python 2中,输入将尝试按代码评估您输入的内容。您可以尝试向脚本添加一个打印(sys.version)并查看它打印的内容。 – paep3nguin
此外,我敢肯定,块[单词]将无法正常工作,因为你正在尝试,因为单词是一个字符串,而不是列表的数字索引。你可以改为“为我,在枚举(块)”和“块[我] = ...” – paep3nguin