我有以下Python词典:
myDict = {"how":"como", "you?":"tu?", "goodbye":"adios", "where":"donde"}
使用类似于:"How are you?"
的字符串,我希望将以下结果与myDict
进行比较:
"como are tu?"
正如您所看到的,如果一个单词没有像“are”那样出现在myDict
中,那么结果会显示为它。你知道吗
这是我的代码直到现在:
myDict = {"how":"como", "you?":"tu?", "goodbye":"adios", "where":"donde"}
def translate(word):
word = word.lower()
word = word.split()
for letter in word:
if letter in myDict:
return myDict[letter]
print(translate("How are you?"))
结果只得到了第一个字母:como
,那么我没有得到整个句子又做错了什么呢?你知道吗
感谢您的帮助!你知道吗
当您调用
return
时,当前正在执行的方法被终止,这就是您的方法在找到一个单词后停止的原因。要使方法正常工作,必须附加到String
中,该String
作为局部变量存储在方法中。你知道吗下面是一个函数,它使用列表理解来翻译
String
,如果它存在于dictionary
:示例:
函数在第一次碰到
return
语句时返回(退出)。在这种情况下,这永远是第一个词。你知道吗你应该做的是列一个单词列表,如果你看到当前的返回,你应该添加到列表中。你知道吗
添加每个单词后,可以在末尾返回列表。你知道吗
附言:你的术语很混乱。你有的是短语,每个短语都是由单词组成的。”这是一个短语“是一个短语,由4个单词组成:“This”,“is”,“a”,“短语”。字母应该是单词的单独部分,例如“This”中的“T”。你知道吗
问题是,您将返回映射到词典中的第一个单词,因此您可以使用它(我更改了一些变量名,因为这有点混乱):
输出:
相关问题 更多 >
编程相关推荐