2014-09-01 101 views
0

我是新來學習python,我正在研究一個迷你翻譯器,將英語譯成西班牙語和西班牙語譯成英語。用戶可以選擇輸入'show'來查看英文或西班牙文列表。Python-列表到詞典

有人可以幫助我理解,爲什麼當他們鍵入列表中的英語或西班牙語單詞時,它不會翻譯該單詞。當我說它沒有翻譯,沒有任何反應,我可以繼續輸入新單詞,它什麼都不做。 'show'部分雖然正常工作。

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)) 
spanish_to_english = dict(zip(spanish_list, english_list)) 

def translate(word): 
    translation = english_to_spanish.get(word) 
    if translation: 
     return translation 

    translation = spanish_to_english.get(word) 
    if translation: 
     return translation 

    raise Exception('Word {0} does not exists'.format(word)) 

print("Welcome to the English <--> Spanish Dictionary") 
while True: 
    word = input("> ") 
    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: 
     try: 
      translate(word) 
     except Exception as e: 
      print ("That wasn't a option") 

任何幫助,將不勝感激。謝謝

+0

你會得到什麼錯誤?你使用的是什麼版本的Python? – inspectorG4dget 2014-09-01 05:47:45

+0

我正在使用3.41,當我輸入文字時,沒有任何反應,除非輸入'show',否則我可以繼續輸入任何內容。 – 2014-09-01 05:49:52

回答

1

您從translate返回的單詞但從來沒有打印它。將行更改爲結尾(在try之內)至print(translate(word))

-1

在Python中,字典是使用如下所示的'鍵值對'創建的。

dict = {"fire":"fuago", "apple":"manzana" ...} 

在您的代碼中,您使用zip函數從列表的tapple生成tapples列表。 所以你的代碼像下面(zip函數後執行)

dict = {("fire","fuago"),("apple","manzana") ...} 

您使用tapples而不是鍵值對是你的問題的最主要的原因,我猜。

+0

首先,它們是「元組」。其次,你是完全錯誤的;你的第二個片段是一組二元組,它不是**所產生的。 'dict'需要一個可迭代的二元組,並認爲它們'(key,value)'非常愉快地配對。 'dict(zip(keys,values))'是創建字典的一種常用方式,並且完美地工作。 – jonrsharpe 2014-09-01 07:22:15