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

2024-09-30 20:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

one uno
two dos
three tres
hello hola

我想把这个文件读入字典,打印出用户输入的英语单词的西班牙语翻译。如果英文单词不存在,则应打印“not there”语句。我有一些代码,但当我运行它总是打印出“不在那里”,无论我输入什么。我能做些什么来解决这个问题?谢谢

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

Tags: 文件toindeflineexitvalword
2条回答

两大问题:

if 'word' in newDict:

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

(word, val) = line.split()

覆盖传递到函数中的任何word,使其等于文件中的每个英文单词。将其更改为eng,spa = line.split()或其他形式,以不覆盖传递到函数中的参数

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

相关问题 更多 >