2016-12-16 28 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