我正在尝试使用字典翻译短语,方法是将该短语中的每个单词与字典的键匹配。
我可以通过交互式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”以外的任何内容。
答案 0 :(得分: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)
正如@TShepang所建议的那样,最好避免使用诸如string和dict之类的built_in名称作为变量名。