python - 从 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)
推荐阅读
- linux - 谁在调用 brk(NULL),为什么?
- javascript - 如何从视图文件中检索变量到控制器
- json - 如何将 JSON 数据下载到 TableView 中?
- c# - 如何在c#中创建一个可以将类型存储为值的字典
- reactjs - 如何在本机反应中对用户联系人数组进行排序
- c - 我在方程中输入一个双整数,但一直得到 0
- java - 如果未在 android 中使用 volley 选择,如何上传可选图像
- python - 从我创建的列表中仅提取一个元素
- javascript - 通过选中/取消选中一个复选框来选中/取消选中多个复选框
- android - 反转视频并循环2次ffmpeg