开发者

Dictionaries in Python

开发者 https://www.devze.com 2023-01-19 20:54 出处:网络
I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don\'t know how to continue. Please, help.

I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don't know how to continue. Please, help. Dictionary is a text document where tab separates english and estonian words.

file = open("dictionary.txt","r")

eng = []

est = []

while True :
    lines = file.readline()

    if lines == "" :
        bre开发者_如何学Goak

    pair = lines.split("\t")
    eng.append(pair[0])
    est.append(pair[1])

    for i in range......

Please, help.


For a dictionary, you should use the dictionary type which maps keys to values and is much more efficient for lookups. I also made some other changes to your code, keep them if you wish:

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

Mind that the reverse lookup (Estonian to English) is not so easy. If you need that, too, you might be better off creating a second dictionary variable with the reversed key-value mapping (estToEngDict[pair[1]] = pair[0]) because lookup will be a lot faster than your list-based approach.


It would be better to use the appropriately named dict instead of two lists:

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

Then to use it:

translated = d["hello"]

You should also note that when you call readline() that the resulting string includes the trailing new-line so you should strip this before storing the string in the dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消