我有一个问题。我想制作一本将英语单词翻译成爱沙尼亚语的词典。我开始了,但不知道如何继续。请帮忙。 字典是一个文本文档,其中制表符分隔英语和爱沙尼亚语单词。
file = open("dictionary.txt","r")
eng = []
est = []
while True :
lines = file.readline()
if lines == "" :
break
pair = lines.split("\t")
eng.append(pair[0])
est.append(pair[1])
for i in range......
请帮忙。
最佳答案
对于字典,您应该使用将键映射到值并且查找效率更高的字典类型。我还对您的代码进行了一些其他更改,如果您愿意,请保留它们:
engToEstDict = {}
# The with statement automatically closes the file afterwards. Furthermore, one shouldn't
# overwrite builtin names like "file", "dict" and so on (even though it's possible).
with open("dictionary.txt", "r") as f:
for line in f:
if not line:
break
# Map the Estonian to the English word in the dictionary-typed variable
pair = lines.split("\t")
engToEstDict[pair[0]] = pair[1]
# Then, lookup of Estonian words is simple
print engToEstDict["hello"] # should probably print "tere", says Google Translator
请注意,反向查找(爱沙尼亚语到英语)并不那么容易。如果您也需要,您可能最好使用反向键值映射创建第二个字典变量 (estToEngDict[pair[1]] =pair[0]
),因为查找将是比基于列表的方法快得多。
关于python - Python 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897460/