''' Purpose: translate user text to English ''' # get access to url support import url # CS 1112 translation dictionary -- entries are of form: word,translation BABEL_FISH_URL = 'http://www.cs.virginia.edu/~cs1112/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 = {} # This is us initializing an empty dictionary! # This is the part where we build our dictionary! for row in dataset: # For each row in our dataset w1, w2 = row # Get the w1, w2 from the two comma separated items in the row # list generated in our dataset word_mappings [ w1 ] = w2 # Create a mapping between w1 and w2 #print( word_mappings ) # let's see what we got so far # get the user text to be translated reply = input( 'Enter phrase to be translated: ' ) # convert reply into a list of words to_be_translated = reply.split() # We've taken our input string (some assortment of words in different # languages and we wanna translate each word into English) and create # a string of the translated words. # process the list word by word -- that is, build up the output phrase # word by word sentence = "" # We initialize our accumulator to be an empty string # Why? Because we wanna translate each word as we go and add it to our # big string of translated words # So basically if our word is not in our dictionary and can't be # translated it's gonna be like >word< in our output string for word in to_be_translated : # translate word lowercase_word = word.lower() # get access to a lower-case version of the word. # first check to see if the word is our dictionary # If word is in our dictionary, then we can get its translation. if ( word in word_mappings ) : # Is word one of my keys? translation = word_mappings.get( word ) elif ( lowercase_word in word_mappings ) : # Is a lowercase version of the word one of my keys? translation = word_mappings.get( lowercase_word ) translation = translation.capital() # get the translation to match the character case pf the original else: # word is not in the dictionary translation = ">" + word + "<" # We needed to set translation whether it's in our dictionary or not sentence = sentence + translation + " " # Remember that sentence is our accumulator # so we go through and we get the translation of each word # and add it to our string with a space separating each translation # print translation print ( sentence )