gpt4 book ai didi

python - Python 中的字典

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:32 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com