2010-10-09 196 views
2

我遇到问题。我想制作一本将英语单词翻译成爱沙尼亚语的词典。我开始了,但不知道如何继续。请帮忙。 词典是一个文本文件,其中标签分隔英文和爱沙尼亚语单词。Python中的词典

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...... 

请帮忙。

回答

3

对于字典,您应该使用将键映射到值的字典类型,并且对查找效率更高。我还做了一些其他修改了代码,让他们,如果你想:

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比基于列表的方法快很多。

+0

xreadlines很长时间不推荐使用。 '对于f中的行:if line:eng,est = line.split(“\ t”)'等 – 2010-10-09 19:24:41

+0

@ THC4k:对,修正它。 – AndiDog 2010-10-09 19:28:33

1

这将是更好地使用适当命名的dict而不是两个列表:

d = {} 
# ... 
d[pair[0]] = pair[1] 

然后使用它:

translated = d["hello"] 

你还应该注意的是,当你调用的ReadLine()的结果字符串包含尾随的换行符,因此在将字符串存储在字典中之前应该将其去掉。