python - Python 中的字典

标签 python dictionary iteration

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

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

请帮忙。

最佳答案

对于字典,您应该使用将键映射到值并且查找效率更高的字典类型。我还对您的代码进行了一些其他更改,如果您愿意,请保留它们:

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]),因为查找将是比基于列表的方法快得多。

关于python - Python 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897460/

相关文章:

python - 带有夹层和模板的 django 静态 url

python - 用同一个键合并两个字典

python - 交叉文档字段以确定最近的

Swift For In Loop 遍历一组自定义类不起作用

python - DiGraph networkx 的大型网络实例的最快迭代是什么?

python - 如何在网速慢时停止pyautogui并恢复之前的程序代码

python - 使用 numpy 将数组写入标准输出

swift - 检查字符串中的字符在字典中是否匹配

c++ - 递归分配没有给出正确的输出

python - 如何离线将 python 模块导入 Pycharm