對於字典,您應該使用將鍵映射到值的字典類型,並且對查找效率更高。我還做了一些其他修改了代碼,讓他們,如果你想:
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