[英]Trying to remove specific item from json file
我正在尝试删除“注释”列表中的所有项目,并将值 7 作为“类别 ID”。 每次运行代码时,function 都会返回一个未删除此特定条目的列表。 最终目标是更改大量特定标签的类别 ID,并删除所有其他标签。
这是我现在的代码
annotations_test = 'test_annotations/_annotations.coco_test.json'
annotations_train = 'train/_annotations.coco.json'
def delete(annotations_test):
with open(annotations_test, "r") as data_file:
data = json.load(data_file)
for i in range(1, len(data["annotations"])):
len_after=len(data["annotations"])
if i == len_after:
print(data)
return data
if data["annotations"][i]['category_id'] == 7:
del data["annotations"][i]
i = i - 1
JSON 文件如下所示。
{
"categories": [
{
"id": 0,
"name": "Teeth",
"supercategory": "none"
},
],
"images": [
{
"id": 0,
"license": 1,
"file_name": "Output13_jpg.rf.7422a2210c5a09d832d2e0c3d8a765ee.jpg",
"height": 416,
"width": 416,
"date_captured": "2022-04-22T13:07:04+00:00"
},
{
"id": 1,
"license": 1,
"file_name": "Output9_jpg.rf.f8ae8e69ef667a8883518fafff1470c0.jpg",
"height": 416,
"width": 416,
"date_captured": "2022-04-22T13:07:04+00:00"
}
],
"annotations": [
{
"id": 0,
"image_id": 0,
"category_id": 7,
"bbox": [
179,
43,
20.5,
23.5
],
"area": 481.75,
"segmentation": [],
"iscrowd": 0
},
{
"id": 1,
"image_id": 0,
"category_id": 3,
"bbox": [
240,
54,
20.5,
23.5
],
"area": 481.75,
"segmentation": [],
"iscrowd": 0
}
在您循环的列表上使用del
不是一个好主意。
如果您想要的是 category_id 不为 7 的注释列表,则可以使用列表理解。
with open(annotations_test, "r") as data_file:
data = json.load(data_file)
return [annotation for annotation in data["annotations"] if annotation['category_id'] != 7]
如果您需要仅更新注释的整个 json 数据。
with open(annotations_test, "r") as data_file:
data = json.load(data_file)
without_7 = [annotation for annotation in data["annotations"] if annotation['category_id'] != 7]
data["annotations"] = without_7
return data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.