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