我试图翻译使用字典的短语,通过将该短语中的每个单词与字典的密钥进行匹配。使用字典翻译短语
我可以通过交互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
我不知道如何设置字符串,将检查除了'你好'以外的任何东西。
为什么你使用'string'呢?为什么不直接将翻译应用于用户的输入? – BrenBarn 2013-03-05 19:57:33
使用'replace'只会导致麻烦:'hello'是'Othello'的一个子字符串,所以如果您也包含小写字母的版本,您可以获得“Othola”.. – DSM 2013-03-05 20:02:20