我正在尝试翻译。
english_List = ["fire","apple","morning","river","wind"]
spanish_List = ["fuego","manzana","mañana","río","viento",]
输入英文单词时,我是否可以这样做,例如"fire"
它会打印出相应的翻译"fuego"
?
答案 0 :(得分:3)
使用字典。您可以创建一个字典,其中映射了英语单词
使用zip()
将"fire"
与"fuego"
,"apple"
与"manzana"
联系起来,使用这两个列表中的相应西班牙语单词,依此类推。然后使用dict()
构建字典。
english_list = ["fire","apple","morning","river","wind"]
spanish_list = ["fuego","manzana","mañana","río","viento"]
english_to_spanish = dict(zip(english_list, spanish_list))
您可以获得英语单词的翻译,然后:
spanish = english_to_spanish['apple']
如果找不到单词,则会引发KeyError
异常。一个更完整的例子可以使用一个函数进行翻译,比如说:
def translate(english_word):
try:
print("{} in Spanish is {}".format(
english_word, english_to_spanish[english_word]))
except KeyError:
print("Looks like Spanish does not have the word for {}, sorry"
.format(english_word))
while True:
word = input() # raw_input in python 2
translate(word)
答案 1 :(得分:1)
使用dict映射相应的单词:
trans_dict = {"fire":"fuego","apple":"manzana","morning":"mañana","river":"río","wind":"viento"}
inp = raw_input("Enter your english word to translate:").lower()
print("{} is {}".format(inp.capitalize(),trans_dict.get(inp," not in my translation dict").capitalize()))
您可以使用zip从列表中制作字典:
english_List = ["fire","apple","morning","river","wind"]
spanish_List = ["fuego","manzana","mañana","río","viento"]
trans_dict = dict(zip(english_List,spanish_List))
使用默认值为trans_dict.get(inp,"not in my translation dict")
的{{1}}将确保用户输入我们的"not in my translation dict"
中不存在的字词,它会打印trans_dict
和避免使用the_word is not in my translation dict"
我们使用keyError
以防用户使用大写字母输入Fire或Apple等..并使用.lower()
输出数据大写。
答案 2 :(得分:0)
您可以使用此功能执行此操作:
def translate(word, english_list, spanish_list):
if word in english_list:
return spanish_list[english_list.index(word)]
else:
return None
但是,正确的方法是使用字典。
答案 3 :(得分:0)
我认为最好的方法是使用字典。 例如:
d = {"fire": "fuego", "apple": "manzana"}
然后检索翻译:
d.get("fire", "No translation")
顺便说一句。在python.org上,您将找到有关如何学习Python的精彩文档:
https://wiki.python.org/moin/BeginnersGuide
我认为你应该从这里开始: