我的任务是使用嵌套的if
语句来构造一个简单的翻译器。是的,我知道这是一种糟糕的方式,但这就是作业所说的。这是我到目前为止所做的:
def translate(word, language):
'''
Takes as parameters a string to translate,
and a second string as the language to translate to.
Returns the original word, the language, and the word's
translation in the entered language.
'''
en_word = word.lower()
lang = language.lower()
# French
if lang == "french":
if en_word == "cat":
print("chat")
if lang == "french":
if en_word == "dog":
print("chein")
# German
if lang == "german":
if en_word == "cat":
print("katze")
if lang == "german":
if en_word == "dog":
print("hund")
# Spanish
if lang == "spanish":
if en_word == "cat":
print("gato")
if lang == "spanish":
if en_word == "dog":
print("perro")
translate('cat', 'french')
例如,在被称为translate('cat', 'french')
后,输出应为:
The translation of cat in French is chat
实际上,我的函数找到并打印出正确的单词。我尝试使用return
语句,例如
return en_word, 'French', 'chat'
以及
print('The translation of', translate[0], 'into', translate[1], 'is', translate[2])
但弹出错误消息TypeError: 'function' object is not subscriptable
。我可以在函数中的print
语句的每一端放置几乎相同的if
语句,但这看起来非常不优雅。
如何让函数返回要插入通用打印语句的英语单词,语言和翻译单词?
答案 0 :(得分:0)
用return语句替换print函数?
答案 1 :(得分:0)
以下是如何重新构建代码的示例。
def translate(word, language):
en_word = word.lower()
lang = language.lower()
if lang == "french":
if en_word == "cat":
return "chat"
elif en_word == "dog":
return "chein"
elif lang == "german":
if en_word == "cat":
return "katze"
elif en_word == "dog":
return "hund"
elif lang == "spanish":
if en_word == "cat":
return "gato"
elif en_word == "dog":
return "perro"
myword = 'cat'
mylanguage = 'french'
res = translate(myword, mylanguage)
print('The translation of {0} in {1} is {2}'.format(myword, mylanguage.title(), res))
<强>解释强>
elif
代替不必要的重复if
语句。return
代替print
。str.format
将变量合并到函数外的print
语句中。答案 2 :(得分:0)
我想这是由你的任务指定的,但在现实生活中,我会使用字典词典作为你的...字典的基础,而不是一堆if
语句:
def translate(word,language):
dictionary = {
"french": {"cat":"chat",
"dog":"chien"},
"german": {"cat":"katze",
"dog":"hund"},
"spanish": {"cat":"gato",
"dog":"perro"}
}
return(dictionary.get(language).get(word,word))
这会产生:
>>> translate("cat","french")
'chat'
>>> translate("cat","german")
'katze'
>>> translate("dog","german")
'hund'
>>> translate("mouse","spanish")
'mouse'
如果找不到原始单词,则返回原始单词。您希望为不在字典中的单词或语言构建错误处理,