-1

私はDictionary.txtというファイルを持っています。このファイルには、英語の単語が 1 つ、スペースが 1 つ、各行にその単語のグルジア語訳が含まれています。

私の仕事は、対応する単語のない英語の単語が辞書にある場合はいつでもエラーを発生させることです (たとえば、英語の単語に翻訳がない場合)。

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

3 に答える 3

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()2 つの値が見つからない場合、アンパックは行われず、 aValueErrorが発生します。例外をキャッチし、簡単な警告を出力します。else例外 (句)が見つからない場合、エントリは python 辞書に追加されます。

これにより、元のファイルの行の順序が保持されないことに注意してください。

于 2014-06-12T08:32:10.940 に答える