''' Purpose: translate user text to English ''' import url def setup(): # CS 1112 translation dictionary -- entries are of form: word,translation BABEL_FISH_URL = 'http://www.cs.virginia.edu/~cs1112/datasets/words/babelfish' # get contents of babel fish url dataset = url.get_dataset(BABEL_FISH_URL) # convert csv-based word mappings into dictionary format word_mappings = {} for entry in dataset: foreign, english = entry word_mappings[foreign] = english return word_mappings DEFAULT_DICTIONARY = setup() 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 = '' # empty string accumulator for row in text: # want something else to do translation wor = line( row, dictionary ) # call the line function on row to translate the line txet = txet + wor + '\n' # add the translated line to the accumulator along with a line break return txet def line( string, dictionary = DEFAULT_DICTIONARY ): ''' returns a translation of string, where string is composed of multiple words ''' words = string.split() # split the string into a list of words sdrow = '' for w in words: m = word( w, dictionary) # call the word function to translate the word sdrow = sdrow + m + ' ' # add this to the accumulator return sdrow def word( string, dictionary = DEFAULT_DICTIONARY): ''' returns a translation of the word string, if the translation is unknown return string within <> ''' if ( string in dictionary ): result = dictionary.get( string ) # translate the word else: result = '<' + string + '>' return result # name is a built in python variable; # it is set to main if you are running that program directly # it is set to the name of the module if it is bein run as a module if ( __name__ == '__main__' ): print( word( 'lapiz' ) ) print( line( 'como esta' ) ) print( glot( 'como esta\n hacer')) #else: # print( __name__ ) # This was done in multiple functions because it is cleaner code # allows for these actions to be repeated in the future