Python 抛出错误(在终端显示),然后继续执行其余代码

-1 投票
3 回答
1269 浏览
提问于 2025-04-18 09:31

我有一个文件叫做 dictionary.txt,里面每一行都包含一个英文单词,后面跟着一个空格,然后是这个单词的格鲁吉亚语翻译。

我的任务是,当发现某个英文单词没有对应的翻译时,就要抛出一个错误(比如说,如果这个英文单词没有翻译的话)。

如果我抛出一个 ValueError 或类似的错误,代码就会停止运行。你能给我一个例子吗?(如果没有其他选择的话,可以用 try 语句)。

def extract_word(file_name):
    final = open('out_file.txt' ,'w')
    uWords = open('untranslated_words.txt', 'w+')
    f = open(file_name, 'r')
    word = ''
    m = []
    for line in f:
        for i in line:
            if not('a'<=i<='z' or 'A' <= i <= 'Z' or i=="'"):
                final.write(get_translation(word))
            if word == get_translation(word) and word != '' and not(word in m):
                m.append(word)
                uWords.write(word + '\n')
                final.write(get_translation(i))
                word=''
            else:
                word+=i
    final.close(), uWords.close()

def get_translation(word):
    dictionary = open('dictionary.txt' , 'r')
    dictionary.seek(0,0)
    for line in dictionary:
        for i in range(len(line)):
            if line[i] == ' ' and line[:i] == word.lower():
                return line[i+1:-1]
    dictionary.close()
    return word

extract_word('from.txt')

3 个回答

0

抛出错误主要是为了让程序能够做出反应或者停止运行。在你的情况下,可能更合适的做法是使用日志API来向控制台输出一个警告信息。

import logging

logging.warning('Failed to find Georgian translation.') # will print a warning to the console.

这将会产生以下输出:

WARNING:root:Failed to find Georgian translation.
0

你可能应该看看这个链接

f = open('dictionary.txt')
s = f.readline()
try:
    g = translate(s)
except TranslationError as e:
    print "Could not translate" + s

假设translate(word)会抛出一个翻译错误(TranslationError)。

0

这个问题不是很清楚,但我觉得你可能需要这样的代码:

mydict = {}
with open('dictionary.txt') as f:
    for i, line in enumerate(f.readlines()):
         try:
              k, v = line.split() 
         except ValueError:
              print "Warning: Georgian translation not found in line", i   
         else:
              mydict[k] = v

如果 line.split() 没有找到两个值,就不会进行拆分,这时会出现一个 ValueError 错误。我们会捕捉这个错误并打印一个简单的警告。如果没有错误发生(也就是 else 这部分),那么这个条目就会被添加到 Python 的字典里。

需要注意的是,这样做不会保留原文件中的行顺序。

撰写回答