2010-10-09 203 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()的結果字符串包含尾隨的換行符,因此在將字符串存儲在字典中之前應該將其去掉。