【问题标题】:Python - try/except method for an existing textfilePython - 现有文本文件的 try/except 方法
【发布时间】:2020-03-29 12:18:40
【问题描述】:

对于下面的代码,我应该编写三个单独的 try/except 块,分别对以下三个错误做出反应:

1) 文件不可用 2) 文件中的一行包含的元素数量少于预期 3) 在字典中找不到用户的条目作为键

另外,第二个错误不应该完成程序。文本文件中不正确的行应该被跳过,所以字典应该有三个键值对。 文本文件的内容如下所示。最后,程序应该能够同时打印左词(原词)和右词(翻译):

猎犬

猫卡茨

问号

雪花

这是以下代码:


with open(filename, "r", encoding="utf8") as dictionaryfile:

    for line in dictionaryfile:

        elements_from_line = line.split()

        word = elements_from_line[0]

        translation = elements_from_line[1]

        translationdictionary[word] = translation

inputword = input("Welches Wort soll übersetzt werden? >")

correct_translation = translationdictionary[inputword]

print("Das Eingabewort:\t{}\nDie Übersetzung:\t{}".format(inputword, correct_translation)) 

【问题讨论】:

    标签: python-3.x function try-catch except


    【解决方案1】:

    如果你必须在 try-except 块中完成所有操作,它可能看起来像这样:

    • 如果文件不存在 - 捕获OSError
    • 如果文件中某行包含的元素少于预期 - 捕获IndexError
    • 如果用户 input 不在字典中 - 这意味着我们必须捕获 KeyError

    所以,在那之后我们可以尝试这样的事情:

    编辑您的代码:

    filename = 'ala.txt'
    translationdictionary = {}
    try:
        with open(filename, "r", encoding="utf8") as dictionaryfile:
            for line in dictionaryfile:
                elements_from_line = line.split()
                try:
                    word = elements_from_line[0]
                    translation = elements_from_line[1]
                    translationdictionary[word] = translation
                except IndexError:
                    continue  # skip line
    except OSError:  # can not find file
        print('File not found')
    
    inputword = input("Welches Wort soll übersetzt werden? >")
    
    try:
        correct_translation = translationdictionary[inputword]
        print("Das Eingabewort:\t{}\nDie Übersetzung:\t{}".format(inputword, correct_translation))
    except KeyError:  # lack of key in dict
        print('Can not find input in dict')
    

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2019-06-26
      • 2013-11-13
      • 1970-01-01
      • 2021-06-22
      • 2018-03-19
      • 2011-04-25
      • 2021-08-02
      • 2019-07-14
      相关资源
      最近更新 更多