''' Purpose: translate user text to English ''' import url # default dictionary location -- its entries are of form: word,translation DEFAULT_URL = 'http://www.cs.virginia.edu/~cs1112/datasets/words/babelfish' # get contents of the url as the default dictionary DEFAULT_DICTIONARY = url.get_dictionary( DEFAULT_URL ) def glot( text, dictionary = DEFAULT_DICTIONARY ) : ''' Returns a translation of text according to dictionary, where text may have embedded \n's ''' text = text.split( '\n' ) # split text into a list of lines txet = '' # initialize accumulator for row in text : # need to process each row of the text wor = line( row, dictionary ) # call line() on row to translate it txet = txet + wor + '\n' # add translation to the accumulator # along with a line break return txet # return translation def line( string, dictionary = DEFAULT_DICTIONARY ) : ''' Returns a translation of string according to dictionary, where string is composed of multiple words ''' words = string.split() # split string into list of words sdrow = '' # initialize accumulator for w in words : # need to process each word m = word( w, dictionary ) # call word() on w to translate it sdrow = sdrow + m + ' ' # add translation to the accumulator return sdrow # return translation def word( string, dictionary = DEFAULT_DICTIONARY ) : ''' Returns a translation of the word string according to dictionary. if the translation is unknown return the word within <> ''' w = string.strip() # clean up word if ( w in dictionary.keys() ) : # check if word is known m = dictionary.get( string ) # it is, so translate it else : # otherwise, it is not m = '<' + w + '>' # word is flagged return m # return translation if ( __name__ == '__main__' ) : print( word( 'lapiz' ) ) print() print( line( 'como esta eso' ) ) print() print( glot( 'tun vous savez hvor\nmi pencil ist' ) ) print() DIGIT_URL = 'http://www.cs.virginia.edu/~cs1112/words/digits' d = url.get_dictionary( DIGIT_URL ) print( glot( '0 O 1 2 3 4 5', dictionary = d ) )