将文件读入字典并打印出值

时间:2015-12-02 16:34:48

标签: python dictionary

我有一个包含两列的文件:

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()

2 个答案:

答案 0 :(得分:0)

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")

答案 1 :(得分:0)

两个主要问题:

if 'word' in newDict:

检查包含“word”(它可能不是)的文字字符串是否在你的dict中。将其更改为:if word in newDict: print newDict[word]

(word, val) = line.split()

覆盖您传递给函数的word等于文件中每个英文单词的内容。将其更改为eng,spa = line.split()或其他不同的内容,以不覆盖传递给函数的参数