2015-12-02 40 views
1

我有兩列的文件:讀取文件到詞典並打印出的值

one uno 
two dos 
three tres 
hello hola 

我想讀這個文件放到一個字典,並打印出英文單詞的用戶的西班牙語翻譯已進入。如果英文單詞不存在,則應打印出「不存在」聲明。我有一些代碼,但是當我運行它時總是打印出「不存在」,無論我輸入什麼。我能做些什麼來解決這個問題?由於

def spanish(word): 
    newDict = {} 
    spanishfile = open("eng2sp.txt","r") 
    for line in spanishfile: 
     (word, val) = line.split() 
     newDict[str(word)] = val 
     if 'word' in newDict: 
      print(newDict['word']) 
     else: 
      print("Not there") 



def main(): 
    word = str(input("Please enter the English word you would like to translate or enter EXIT to quit: ")) 
    while word != "EXIT": 
     spanish(word) 
     word = str(input("Please enter the English word you would like to translate or enter EXIT to quit: ")) 

main() 

回答

1

在你spanish()功能,你命名的參數和局部變量具有相同的名稱,然後你不檢查,對您的newDict的說法,而是串word,這將使完美的意義,爲什麼你總是得到"Not there",再加上你不需要newDict[str(word)] = val,因爲你已經把它讀作string

這是你的解決辦法:

def spanish(word_lookup): 
    with open("eng2sp.txt","r") as spanishfile: 
     newDict = dict(line.split() for line in spanishfile) 
    if word_lookup in newDict: 
      print(newDict[word_lookup]) 
    else: 
     print("Not there") 
+0

@BobSmith ...我更新了我的答案,實際上'for'循環一直循環直到文件結束,因此我添加了只要找到一個匹配項,''return'語句就會從'西班牙語'函數中存在 –

+0

如果我輸入「1」,就會修復它,但是如果我輸入「2」,我仍然會得到「不存在」,那麼「dos」或如果我輸入「三」,我會得到「不存在」,「不存在」,「tres」 –

+0

@BobSmith ...檢查更新... –

0

個兩個主要問題:

if 'word' in newDict: 

檢查是否含有「字」(它有可能心不是)是在你的字典文本字符串。更改到:無論word你在文件傳遞到你的函數等於每個英文單詞if word in newDict: print newDict[word]

(word, val) = line.split() 

覆蓋。將其改爲類似eng,spa = line.split()或類似的東西以不覆蓋您傳遞到您的函數的參數