使用字典翻译短语

iKy*_*aki 1 python

我试图通过将该短语中的每个单词与字典的键匹配来使用字典翻译短语.

http://paste.org/62195

我可以通过交互式shell很好地翻译它,但是当涉及到实际的代码时:

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
Run Code Online (Sandbox Code Playgroud)

我不确定将字符串设置为什么来检查"Hello"以外的任何内容.

jur*_*eza 6

正如大家提到的那样,替换不是一个好主意,因为它匹配部分单词.

这是使用列表的变通方法.

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)
Run Code Online (Sandbox Code Playgroud)

正如@TShepang所建议的那样,避免使用诸如string和dict之类的built_in名称作为变量名是一个好习惯.