# Exercise 4A # Natural language translation. # # Author: David Watt. # English-French dictionary ... dictionary = { \ 'a' : 'un' , \ 'the' : 'la' , \ 'is' : 'est' , \ 'she' : 'elle' , \ 'has' : 'a' , \ 'sees' : 'voit' , \ 'see' : 'voyez' , \ 'behold' : 'voila' , \ 'of' : 'de' , \ 'my' : 'ma' , \ 'her' : 'sa' , \ 'pen' : 'plume' , \ 'aunt' : 'tante' , \ 'mother' : 'mere' , \ 'child' : 'enfant' } def translate_word (word): "Return the translation of word using dictionary, \ or '????' if word is not in dictionary." if word in dictionary.keys(): return dictionary[word] else: return '????' def translate_phrase (phrase1): "Return the translation of phrase1 using dictionary." len1 = len(phrase1) phrase2 = '' i = 0 while i < len1: if phrase1[i].isalpha(): start = i i += 1 while i < len1 and phrase1[i].isalpha(): i += 1 word1 = phrase1[start:i] word2 = translate_word(word1) phrase2 += word2 else: punct = phrase1[i] phrase2 += punct i += 1 return phrase2 def translate (source_name, target_name): "Translate the contents of the file named source_name, \ writing the result to the file named target_name." source_file = open(source_name, 'r') target_file = open(target_name, 'w') source_line = source_file.readline() while len(source_line) > 0: target_line = translate_phrase(source_line) target_file.write(target_line) source_line = source_file.readline() source_file.close() target_file.close()