[英]Iterate Through a Dictionary in Python
我有一个函数,它接受一个表示西班牙语句子的字符串参数并返回一个新字符串,该字符串分别是英语句子的翻译。
根据我的练习,我必须使用翻译功能中出现的词典词来翻译句子中的每个词。
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”))
你对我如何解决我独自尝试但没有成功的问题的想法
你应该遍历句子,而不是字典。 在大多数情况下,如果您需要迭代字典,您可能做错了什么。
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
这样的事情怎么样?
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
您可以使用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())
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")
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) 你会得到你想要的句子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.