从txt文件加载字典时缺少值



当我打印字典时,它似乎省略了一半以上的单词。所有的单词都超过2个字符,因此应该放在字典中自己的关键字中,但似乎被忽略了。为了测试,我将一个文件与字典中完全相同的单词进行了比较。其中36个单词被找到,45个单词失踪。

字典里没有的单词。

这本字典的关键字是单词的前两个字母。

d = {}
#Opens the dictionary file from variable.
with open(dictionary, 'r') as f:
#iterates through each line
for line in f:
line_data = f.readline().strip()
#Gets the first to letters of the word to act as key
first_two = line_data[0:2]
#Checks if line is empty
if line_data is None:
break
#Checks if key is already present in dictionary, appends word to list
if first_two in d.keys():
d[first_two].append(line_data)
#If key is not present create a new key and a list for the words.        
elif first_two not in d.keys():
list = [line_data]
d[first_two] = list

编写的程序每隔一行跳过一次:for line in f已经从文件中读取了行,所以f.readline()是多余的,占用了一半的行。试试这个替代品:

for line in f:
line_data = line.strip()
... (the rest as is)

最新更新