我是新來學習python,我試圖編碼從英文到西班牙文的小詞翻譯。我在這裏得到的代碼從英文翻譯成西班牙文和西班牙文翻譯成英文。但是,我想添加一些代碼,允許用戶在輸入'show'時看到單詞列表。我得到了它的代碼,但是當我輸入show時,它只是打印出「除了keyerror」。Python製作詞典
english_list = ["fire","apple","morning","river","wind"]
spanish_list = ["fuego","manzana","mañana","río","viento"]
english_to_spanish = dict(zip(english_list, spanish_list))
def translate(word):
try:
for key,value in english_to_spanish.items():
if key == word:
print("{0} in Spanish is {1}".format(
word, english_to_spanish[word]))
elif value == word:
print("{0} in English is {1}".format(
word, key))
except KeyError:
print("That wasn't an option"
.format(translate))
print("Welcome to the English <--> Spanish Dictionary")
while True:
word1 = input("> ")
translate(word1)
這裏是我認爲會在用戶輸入'show'時向用戶顯示單詞列表的代碼。
if word == 'show':
wordlist = input("Would you like to see the English or Spanish wordlist?")
if wordlist == 'english':
print(english_list)
elif wordlist == 'spanish':
print(spanish_list)
else:
print("That wasnt an option")
如果有人能夠幫助我在這裏,將不勝感激。 感謝
當然, 「秀」引發了一個關鍵錯誤 - 它不在列表中。代碼發佈在底部的應該工作(*假設*'translate'沒有被調用,並且它被放在適當的位置)。顯示*實際代碼*很重要。 – user2864740 2014-08-31 08:34:35
您的原始代碼使用'word1',而不是'word',用於用戶輸入。 – 2014-08-31 08:36:57