""" Purpose: translate user text to English """ import url DEFAULT_URL = 'http://www.cs.virginia.edu/~cs1112/words/babel' DEFAULT_DICTIONARY = url.get_dictionary( DEFAULT_URL ) def passage( text, dictionary = DEFAULT_DICTIONARY) : """ returns a string translation of text according to dictionary, where text may have embedded \n's """ lines = text.split( "\n" ) # split text into a list of lines result = "" # result to be an accumulation of line translations for string in lines : translation = line( string, dictionary ) result = result + translation + "\n" # add translation to result return result # return accumulated translations def line( text, dictionary = DEFAULT_DICTIONARY ) : """ returns a translation of text according to dictionary, where text is composed of zero or more words """ words = text.split() # split text into a list of words result = "" # result to be an accumulation of word translations for string in words : translation = word( string, dictionary ) # we can call word() here to get the translation or flag each word result = result + translation + " " # add translation to result return result def word( string, dictionary = DEFAULT_DICTIONARY) : """ returns a translation of the string according to dictionary, where string is composed of a single word. if the translation is unknown the function return the word within <> """ # print( dictionary ) adding print() statements is a great way to figure out what's happening if ( string in dictionary ) : # do we know what the word translates to result = dictionary.get( string ) # yes: so it is our result else : result = "<" + string + ">" # no: so flag it for the result return result # return the translation if ( __name__ == '__main__' ) : # test translating a single word translation = word( 'lapiz' ) print( translation ) print() # test translating a single line translation = line( 'como esta eso' ) print( translation ) print() # test translating two lines translation = passage( 'tun vous savez hvor\nmi pencil ist' ) print( translation ) print() # test translating a passage text = """ dubailte dubailte kesusahan und guaio umlilo adolebitque und ketel bombolla umucu di una pantanoso neidr dans der ketel bouyi und cuire oog di tritons und kaki di rano yun di fledermoyz und lingua di chien viperae foarke und blyn cuc stik moo fotur und ovlet tis pre eng viehatys di voimakas guaio mag un inferno salda bouyi und bombolla """ translation = passage( text ) print( translation ) # test translating with a non-default dictionary digits = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine' } translation = passage( 'O \n 0 1 2 3 4 5', dictionary = digits ) print( translation ) print()