我从“在Python中自动化无聊的事情”一书中用Python语言编写了一个MadLib程序。我确信我的程序会这样做,但当用户需要输入时,我总是得到这个奇怪的"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()发布于 2016-12-16 13:03:27
我认为问题在于代码实际上是在Python2中运行的,其中输入函数实际上试图运行用户的输入,就像它是代码一样。比较Python 2和Python 3的input()文档。所以你会得到一个NameError,因为Python试图把你输入的东西当作一个变量,而这个变量并不存在。如果你想让它在Python2中工作,只需将input替换为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()https://stackoverflow.com/questions/41177344
复制相似问题