首页 > 解决方案 > 从 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

标签: pythondictionary

解决方案


编写的程序每隔一行跳过:for line in f已经从文件中读取了这些行,所以f.readline()是多余的,并且正在吃掉你的一半。试试这个替换:

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

推荐阅读