2013-03-05 58 views
1

我试图翻译使用字典的短语,通过将该短语中的每个单词与字典的密钥进行匹配。使用字典翻译短语

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 

我不知道如何设置字符串,将检查除了'你好'以外的任何东西。

+0

为什么你使用'string'呢?为什么不直接将翻译应用于用户的输入? – BrenBarn 2013-03-05 19:57:33

+1

使用'replace'只会导致麻烦:'hello'是'Othello'的一个子字符串,所以如果您也包含小写字母的版本,您可以获得“Othola”.. – DSM 2013-03-05 20:02:20

回答

5

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

这是一个使用列表的解决方法。

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) 

正如@TShepang建议是一个很好的做法,以避免使用BUILT_IN名称,如字符串和字典作为变量名。

+0

也许建议Asker避免内置名称作为通用标识符;在这种情况下'dict' – Tshepang 2013-03-05 21:03:58

+0

@jurgenreza:非常感谢。我正在考虑使用拆分,但真的不知道如何编写它。 – iKyriaki 2013-03-05 21:05:26

+0

@Tshepang谢谢你提到,具有讽刺意味的是,这里的字典是一本真正的字典。 :) – jurgenreza 2013-03-05 21:16:52