我正在使用Python编写一个MadLib程序,并使用#34;自动化Python中的无聊事物#34;书。我确信我的程序将会发生,但我一直都会遇到这种奇怪的问题" NameError"当用户需要输入输入时。
这是我的代码。我的计划是在看到消息成功加入后将内容写入文件。
#!/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()
答案 0 :(得分:0)
我认为问题是代码实际上是在 Python 2 中运行,其中输入函数实际上试图像用户代码一样运行用户的输入。比较Python 2和Python 3的input()文档。因此,您会得到一个NameError,因为Python会尝试将您键入的内容视为变量,而该变量不存在。如果您希望它在Python 2中工作,只需将输入替换为 raw_input 。
您将遇到的另一个问题是
chunk[word] = input("Enter %s: " %word)
不起作用,因为word是一个字符串,而chunk需要一个数字作为列表中的索引。要解决这个问题,您只需跟踪for循环中的当前索引即可。一种特殊的Pythonic方法是使用enumerate函数,如下所示:
for i, word in enumerate(chunk):
if word.lower() in breaks:
chunk[i] = input("Enter %s: " %word)
现在一切都应该有效!固定的 Python 3 版本如下:
#!/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 i, word in enumerate(chunk):
if word.lower() in breaks:
chunk[i] = input("Enter %s: " %word)
newMessage = " ".join(chunk)
print(newMessage)
file.close()