''' 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 ) # this is the formatted dictionary obtained from the web and processed through the url module # { 'foreign word' : 'english translation' } # print( 'babelfish_dictionary =', babelfish_dictionary ) # get the user text to be translated reply = input( "Enter phrase to be translated: " ) # convert reply into a list of words words_to_be_translated = reply.split() # initialize translation accumulator # look at each word in the input sentence, find the translation, and then add the translation to our new sentence # which is a string translation = '' # start with the empty string # process the words for translation one by one. each word contributes to the translation # for each word in the input sentence that has been split into a list of words for current_word in words_to_be_translated : # whether current word is in the dictionary, determines our translation action # need to check whether current_word is in the dictionary if ( current_word in babelfish_dictionary ): # if current_word is in babelfish_dictionary # get the translation from the dictionary output_word = babelfish_dictionary.get( current_word ) else: # if current_word is not in the dictionary # we need to take care of the words that don't exist in the dictionary # we need surround the same word with underscores (our UNKNOWN_WORD_DELIMITER) output_word = UNKNOWN_WORD_DELIMITER + current_word + UNKNOWN_WORD_DELIMITER # here, we have our output_word that we want to add to our translated sentence # update the string accumulator translation = translation + output_word + ' ' # add a space after the output so that the words aren't right # next to each other # print translation print( translation )