【发布时间】:2020-11-25 18:51:28
【问题描述】:
我有一个文本文件 (img.txt),其中的数据如下:
0 0.288281 0.618056 0.080729 0.473148
5 0.229427 0.604167 0.030729 0.039815
0 0.554427 0.024537 0.020313 0.041667
0 0.547135 0.018981 0.020313 0.034259
所以我想创建一个字典,其中 .txt 文件作为键,所有行作为值。有点像
dict={'img.txt':['class':0, 'x':0.288281, 'y':0.618056, 'height':0.080729, 'width':0.473148 ],
['class':5, 'x':0.229427, 'y':0.604167, 'height':0.030729, 'width':0.039815 ]}
有没有办法添加值的键(如 class、x、y 等)。同样由于某种原因,在读取文件时,我的代码忽略了类值(如 0,5 等)。这是我的代码:
import os
list_of_files = os.listdir('C:/Users/Lenovo/annotation/')
count =0
my_dict = {}
for file in list_of_files:
if count < 20:
with open(file) as f:
items = [i.strip() for i in f.read().split(" ")]
my_dict[file.replace(".txt", " ")] = items
else:
break
count = count+1
print(my_dict)
这是我的输出:
{'img_ano (1) ': ['0', '0.288281', '0.618056', '0.080729', '0.473148\n5', '0.229427', '0.604167', '0.030729', '0.039815\n0', '0.554427', '0.024537', '0.020313', '0.041667\n0', '0.547135', '0.018981', '0.020313', '0.034259\n4', '0.533073', '0.488889', '0.022396', '0.077778\n4', '0.630469', '0.375926', '0.017188', '0.075926\n4', '0.132031', '0.431944', '0.019271', '0.065741\n4', '0.802083', '0.191204', '0.013542', '0.037963\n4', '0.823958', '0.175000', '0.012500', '0.038889\n4', '0.702083', '0.192130', '0.013542', '0.036111'],.......}
【问题讨论】:
-
为什么不把
items列表改成合适的字典呢? -
你想要一个嵌套字典?
标签: python python-3.x file dictionary yolo