python - 在 Python 中遍历字典
问题描述
我有一个函数,它接受一个表示西班牙语句子的字符串参数并返回一个新字符串,分别是英语句子的翻译。
根据我的练习,我必须使用翻译功能中出现的字典单词来翻译句子中的每个单词。
def translate(sentence): # the function start here
words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}
这是调用函数的方式,调用函数具有要翻译的句子的值:
print(translate("el gato esta en la casa"))
你对我如何解决我独自尝试但没有成功的问题的想法
解决方案
你应该迭代句子,而不是字典。在大多数情况下,如果您需要迭代字典,您可能做错了什么。
def translate(sentence): # the function start here
words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house',
'el': 'the'}
return ' '.join(words[english_word] for english_word in sentence.split())
这将传入西班牙语句子,将其拆分为单词列表(在空格上拆分),查找字典中的每个单词,然后使用空格作为分隔符将所有内容重新组合成一个字符串。
当然,这是一个幼稚的解决方案,不会关心正确的语法。或关于遗漏的单词(提示:使用try-except
或dict.get
处理后者)。
print(translate("el gato esta en la casa"))
# the cat is in the house