iKyriaki
iKyriaki

Reputation: 609

Translating a phrase using a dictionary

I'm attempting to translate a phrase using a dictionary by matching each word in that phrase with a dictionary's key.

http://paste.org/62195

I can translate it just well through the interactive shell, but when it comes to the actual code:

def translate(dict):
    'dict ==> string, provides a translation of a typed phrase'
    string = 'Hello'
    phrase = input('Enter a phrase: ')
    if string in phrase:
         if string in dict:
            answer = phrase.replace(string, dict[string])
            return answer

I'm not sure what to set string to that would check for anything other than 'Hello.'

Upvotes: 1

Views: 5170

Answers (1)

jurgenreza
jurgenreza

Reputation: 6086

As guys mentioned replace is not a good idea since it matches partial words.

Here is a workaround using lists.

def translate(translation_map):
    #use raw input and split the sentence into a list of words
    input_list = raw_input('Enter a phrase: ').split()
    output_list = []

    #iterate the input words and append translation
    #(or word if no translation) to the output
    for word in input_list:
        translation = translation_map.get(word)
        output_list.append(translation if translation else word)

    #convert output list back to string
    return ' '.join(output_list)

As suggested by @TShepang it is a good practice to avoid using built_in names such as string and dict as variable names.

Upvotes: 6

Related Questions