我有一个包含 20 个 .png file 和一个 .json file 的文件夹。 .json file 如下所示
{
"ID":12,
"flags"={},
"shapes":[
{"label":"text",
"points":[[65, 14],[27, 40]],
}
],
"flags"={},
"shapes":[
{"label":"logo",
"points":[[165, 124],[207, 43]],
}
],
"flags"={},
"shapes":[
{"label":"text",
"points":[[54, 24],[17, 53]],
}
]
}
我想为每个 file 中的所有“标签”制作一个 list。我怎样才能做到这一点?
我试过了
import os
import json
path_to_json = './'
contents=[]
for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]:
with open(path_to_json + file_name) as json_file:
data=json.load(json_file)
contents.append(data)
到这里为止看起来还不错,现在我需要为“标签”获取 value 并且以下部分不起作用
l=[]
for i in range(len(contents)):
label= contents[i]['shapes']['label']
l.append(label)
print(l)
回答1
shapes
是一个 list,所以你必须遍历它:
l = []
for content in contents:
for shape in content['shapes']:
l.append(shape['label'])
print(l)