Search code examples
pythonexceptionraiseerror

Python Raise Error (to display in shell) , then do rest of the code


I have a file called dictionary.txt, it contains one word in English, a space and then the Georgian translation for that word in each line.

My task is to raise an error whenever an English word without a corresponding word is found in the dictionary (e.g. if the English word has no translation).

If I raise a ValueError or something like that it stops the code. Could you provide me with an example(using try if there is no other option).

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

Solution

  • The question is not very clear, but I think you may need this kind of code:

    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
    

    If line.split() doesn't find two values, the unpacking does not take place and a ValueError is raised. We catch the exception and print a simple warning. If no exception is found (the else clause), then the entry is added to the python dictionary.

    Note that this won't preserve line ordering in original file.