''' 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" # delimiters for unknown words UNKNOWN_WORD_DELIMITER = "?" # get contents of babel fish url as a dictionary babelfish_dictionary = url.get_dictionary( BABEL_FISH_URL ) # Now we will get a dictionary from the contents of the webpage print( babelfish_dictionary ) # Dictionary of key value pairs where each row of k, v on the webpage is a k:v pair # get the user text to be translated reply = input( "Enter phrase to be translated: " ) # User-entered string of words to translate # convert reply into a list of words words_to_be_translated = reply.split() # We want to translate each of these words using our dictionary one by one below # initialize translation accumulator translation = '' # We are going to build up this string using word translations of each word in words_to_be_translated # process the words for translation one by one. each word contributes to the translation for current_word in words_to_be_translated: # Loop through each word in the list of words we want to translate # whether current word is in the dictionary, determines our translation action if ( current_word in babelfish_dictionary ): # if the current_word is a key in our dictionary meaning = babelfish_dictionary.get( current_word ) # Get the value (the meaning) of that word from the dictionary! else: # the current_word is not in our dictionary (not able to be translated) meaning = UNKNOWN_WORD_DELIMITER + current_word + UNKNOWN_WORD_DELIMITER # ?word? translation = translation + meaning + ' ' # Add each translated meaning of each word to our string translation # print( current_word ) # meaning = babelfish_dictionary.get( current_word ) # Gets value for the key where the key is the current_word # print( 'Current word: ', current_word, 'Meaning: ', meaning ) # translation = translation + meaning + ' ' # print( translation ) # print translation print( translation )