我试图通过将短语中的每个单词与字典的关键字匹配来使用字典翻译短语。
我可以通过交互式 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
我不确定将字符串设置为什么可以检查“Hello”以外的任何内容。
请您参考如下方法:
正如大家提到的,替换不是一个好主意,因为它匹配部分单词。
这是使用列表的解决方法。
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 所建议的,避免使用内置名称(例如字符串和字典)作为变量名是一种很好的做法。
