2016-12-16 66 views
0

我正在使用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() 
+0

您确定代码在Python 3中运行?可能发生的事情是它实际上在Python 2中运行,在Python 2中,输入将尝试按代码评估您输入的内容。您可以尝试向脚本添加一个打印(sys.version)并查看它打印的内容。 – paep3nguin

+0

此外,我敢肯定,块[单词]将无法正常工作,因为你正在尝试,因为单词是一个字符串,而不是列表的数字索引。你可以改为“为我,在枚举(块)”和“块[我] = ...” – paep3nguin

回答

0

我认为这个问题是代码实际上是在运行的Python 2,其中输入函数实际上试图运行用户的输入,如果它的代号。比较Python 2Python 3的input()文档。所以你得到一个NameError是因为Python试图把你输入的任何东西当作一个变量来处理,而这个变量并不存在。如果你想让它在Python 2中工作,只需将输入替换为raw_input

,你会遇到的另一个问题是,

chunk[word] = input("Enter %s: " %word) 

将无法​​正常工作,因为词是字串和块需要数在列表中的索引。为了解决这个问题,您可以简单地跟踪for循环中的当前索引。一个特别的Python的方式做到这一点是与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() 
+0

这实际上确实工作:)!只是要弄清楚为什么没有捕获“动词”关键字。 – Tarrell13