''' 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 glot( text, dictionary = DEFAULT_DICTIONARY) : ''' returns a translation of text according to dictionary, where text may have embedded \n's ''' # So now we're working with text (lots of lines) contents = text.split('\n') # Split on each line and get a list of lines result = "" for each_line in contents: meaning = line( each_line , dictionary ) result = result + meaning + "\n" # Translate each line using line # and add it to our final result with each line separated using "\n" return result def line( string, dictionary = DEFAULT_DICTIONARY ) : ''' returns a translation of string according to dictionary, where string is composed of zero or more words ''' words = string.split() result = "" # accumulator for w in words: meaning = word( w , dictionary ) # call the word function on each w in our list of words # from the line result = result + meaning + " " # add each translated word to my result return result # Remember that we just have this program as a module with function definitions # so the order of where in code sequentially we write the functions doesn't matter # because we can build functions from other defined functions (like word in line) # and we can test everything at the bottom (name == main thing) # since the code is executed at the bottom when all the functions are written ABOVE it. 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 <> ''' # If we find the word in our dictionary, we return the meaning # from the dictionary. Otherwise, we return if ( string in dictionary.keys() ): # if the word is in my dictionary keys meaning = dictionary.get( string ) # give me the meaning from the dict else: # if it's not in my dictionary meaning = "<" + string + ">" # flag the word return meaning # return the meaning (or flag) 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 ) )