我有兩列的文件:讀取文件到詞典並打印出的值
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()
@BobSmith ...我更新了我的答案,實際上'for'循環一直循環直到文件結束,因此我添加了只要找到一個匹配項,''return'語句就會從'西班牙語'函數中存在 –
如果我輸入「1」,就會修復它,但是如果我輸入「2」,我仍然會得到「不存在」,那麼「dos」或如果我輸入「三」,我會得到「不存在」,「不存在」,「tres」 –
@BobSmith ...檢查更新... –