使用Python遍历字典

时间:2020-01-01 15:27:45

标签: 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”))

您对我如何解决问题的想法 我独自尝试没有成功

5 个答案:

答案 0 :(得分:0)

您应该遍历句子,而不是字典。在大多数情况下,如果需要迭代字典,可能是在做错事。

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-exceptdict.get处理后者)。

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

答案 1 :(得分:0)

这样的事情怎么样?

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

答案 2 :(得分:0)

您可以使用console.log(entry)使用简单的字典查找,因此可以处理get

KeyError

答案 3 :(得分:0)

Python字典的工作方式如下:dictionary["key"] = value

对于您的代码,我建议使用句子中的单词作为键。您将获得值。

例如:words["el"] = "the"

def translate(sentence):  #  the function start here
    ret = ''
    words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el' : 'the'}
    for w in words:
        ret += words[w]+" "
    return ret
translate("el gato esta en la casa")

答案 4 :(得分:0)

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

    english_words = sentence.split()
    for word in english_words:
        yield words[word]

result = translate("el gato esta en la casa")
for res in result:
    print (res,end= " ")

我不明白为什么您需要一个发电机,但无论如何

此打印: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'}

    english_sentence = (words[word] for word in sentence.split())
    return type(english_sentence)

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

此打印输出:<class 'generator'>

基本上,如果您使用“ .join(english_words),您将获得所需的句子