在Python中遍历字典

2024-06-17 19:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它接受一个表示西班牙语句子的字符串参数,并返回一个新字符串,分别是英语句子的翻译。你知道吗

根据我的练习,我必须使用translate函数中出现的字典单词来翻译句子中的每个单词。你知道吗

def translate(sentence):  #  the function start here
words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}

这是调用函数的方法,调用函数有被翻译句子的价值:

印刷体(翻译(“el gato esta en la casa”))

你对我如何处理这个问题的看法 我独自一人尝试,但没有成功


Tags: the函数字符串参数字典单词ella
3条回答

您可以使用get使用简单的字典查找,因此,您可以处理KeyError

def translate(sentence):  #  the function start here
    words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}
    return ' '.join(words.get(x, '') for x in sentence.split())

像这样的怎么样?你知道吗

words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}


def translate(sentence):
    splitted_sentence = sentence.split()
    return ' '.join([words[word] for word in splitted_sentence])

print(translate("el gato esta en la casa"))

>> the cat is in the house

你应该反复读这个句子,而不是字典。在大多数情况下,如果你需要迭代一个字典,你可能是做错了什么。你知道吗

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())

这将接收传入的西班牙语句子,将其拆分为单词列表(按空格拆分),查找dict中的每个单词,然后使用空格作为分隔符将所有内容放回一个字符串中。你知道吗

当然,这是一个幼稚的解决方案,不会关心正确的语法。或者关于缺少的单词(提示:使用try-exceptdict.get来处理后者)。你知道吗

print(translate("el gato esta en la casa"))
# the cat is in the house

相关问题 更多 >