大家好,我可以问个问题吗?我一直在处理这个问题代码。我真的需要做我自己的单词翻译器,但问题是当translation_word没有键和值。
代码:
enter = input("Please Enter the word/s: ")
translation_word = {
"ONE": "Uno",
"TWO": "Dos",
"THREE":"Tres",
"FOUR": "Kwatro",
"FIVE": "Singko",
"SIX": "Sais",
"SEVEN": "Syete",
"EIGHT": "Otso",
"NINE": "Nwebe",
"TEN": "Gis",
enter.upper(): enter
}
Keys = enter.upper().split()
print(Keys)
# get translation and join the translated words into a single string
Values = ' '.join(translation_word.get(str(Key)) for Key in Keys)
print(Values)
expected result:
input: one two three eleven
output: Uno Dos Tres eleven
如果我尝试输入一二三,代码实际上是有效的,但是当我添加一些没有KEY&VALUE的东西时,它总是显示错误。
您可以使用一个简单的if语句来检查键是否存在,如果不存在则打印一些东西。例如:
if key in translation_word:
Values = ''.join(translation_word.get(str(Key)) for Key in Keys)
print(Values)
else:
print("This word can't be translated, please enter a different word")