-1

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')
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
temo
  • 612
  • 1
  • 9
  • 25
  • Please show us what you've tried. – merlin2011 Jun 12 '14 at 08:18
  • Please attach your code, Also it's not clear what you are asking. – Kobi K Jun 12 '14 at 08:18
  • 1
    The question was clear to me :/ - You task is simple - create a dictionary from your translation word list. Each key is the English word, and the value is the translated word. If you lookup a key in a dictionary that doesn't exist, then `KeyError` will be raised and just like any other exception, if you don't catch it the program will terminate automatically. To prevent this from happening, you can use the `get()` method of the dictionary, this will return `None` if a key doesn't exist, and then you can print an appropriate message. – Burhan Khalid Jun 12 '14 at 10:07

3 Answers3

0

Raising an error is primarily to allow the program to react or terminate. In your case you should probably just use the Logging API to output a Warning to the Console.

import logging

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

Will result in the following output:

WARNING:root:Failed to find Georgian translation.
Insomniac
  • 446
  • 7
  • 15
  • Thanks but it has to raise error, warning is not the solution but i'll keep it in mind – temo Jun 12 '14 at 09:44
0

You should probably take a look at this

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

Assuming that translate(word) raises a TranslationError of course.

Ariel Voskov
  • 326
  • 3
  • 7
0

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.

  • Got it.Seems I can't use "raise" to do so. i just wanted it to print out like actual error all in red and stuff. Thanks anyways. Sorry for my English – temo Jun 12 '14 at 10:27
  • You might want to check this [question](http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python) to print colors in terminal. – Jaime Rodríguez-Guerra Jun 13 '14 at 10:29
  • 1
    Got it.Thanks man. Finally i talked with teach. and he said it's ok code to stop working after this error ) So it's done with simple raise ValueError("Thing"). I've learnt many new stuff from the comments , Thanks guys – temo Jun 14 '14 at 11:39