对于字典,您应该使用将键映射到值的字典类型,并且对查找效率更高。我还做了一些其他修改了代码,让他们,如果你想:
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]
)创建第二个字典变量,因为lookup比基于列表的方法快很多。
xreadlines很长时间不推荐使用。 '对于f中的行:if line:eng,est = line.split(“\ t”)'等 – 2010-10-09 19:24:41
@ THC4k:对,修正它。 – AndiDog 2010-10-09 19:28:33