擅长:python、mysql、java
<p>你应该反复读这个句子,而不是字典。在大多数情况下,如果你需要迭代一个字典,你可能是做错了什么。你知道吗</p>
<pre><code>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())
</code></pre>
<p>这将接收传入的西班牙语句子,将其拆分为单词列表(按空格拆分),查找dict中的每个单词,然后使用空格作为分隔符将所有内容放回一个字符串中。你知道吗</p>
<p>当然,这是一个幼稚的解决方案,不会关心正确的语法。或者关于缺少的单词(提示:使用<code>try-except</code>或<code>dict.get</code>来处理后者)。你知道吗</p>
<pre><code>print(translate("el gato esta en la casa"))
# the cat is in the house
</code></pre>