使用词典翻译短语
我正在尝试用字典翻译一个短语,方法是把短语中的每个单词和字典里的键进行匹配。
我在交互式命令行中翻译得很好,但在实际代码中:
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.'以外的其他内容。
1 个回答
6
正如大家提到的,使用替换(replace)并不是个好主意,因为它会匹配到部分单词。
这里有一个使用列表的解决方法。
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所建议的,避免使用像字符串(string)和字典(dict)这样的内置名称作为变量名是个好习惯。