python - Python正则表达式(regex),将JSON转换为文本文件进行解析
问题描述
我用 VGG 注释器注释了一些视频帧,它为我提供了JSON
格式的注释,并希望对其进行解析以提取我需要的值(x,y 坐标)。
我查看了该网站上的其他帖子,但似乎没有什么与我的情况相符,因为文件名的长度发生了变化,即。帧号从 0 到 9,然后从 10 到 99、100 到 999、1000 到 9999,增加一位。
我已经尝试import glob
并使用通配符范围、单个字符和星号。
我现在的代码:
#Edited
while count < 1200:
x = data[key]['regions']['0']['shape_attributes']['cx']
y = data[key]['regions']['0']['shape_attributes']['cy']
pts = (x, y)
xy.append(pts)
count += 1
f = open("coordinates.txt", "w")
f.write(xy)
f.close()
JSON 看起来像:
"shape_attributes": {
"name": "point",
"cx": 400,
"cy": 121
},
"region_attributes": {}
}
}
},
"frame48.jpg78647": {
"fileref": "",
"size": 78647,
"filename": "frame48.jpg",
"base64_img_data": "",
"file_attributes": {},
"regions": {
"0": {
"shape_attributes": {
"name": "point",
"cx": 404,
"cy": 114
},
"region_attributes": {}
}
}
编辑:我要将 JSON 转换为.txt
文件并解析它以获得我的值,因为我现在不知道如何直接这样做。
我尝试转换为字符串并在下面解析字符串:这完成了获取 x,y 坐标(3 位整数)的工作,仅附加到我将转换为 (x,y) 的元组列表的列表和打印到文本文件以供以后用作神经网络的标签,我在其中跟踪网球在电视上的网球比赛的坐标。
xy.append(re.findall(r'\b\d\d\d\b', datatxt))
解决方案
您不能在字典中使用通配符键。您是否真的关心密钥 - 是否有您想要忽略的条目,或者您是否很高兴拥有任何/全部?
如果键不重要,则取data.values()
which 将是字典列表,您可以浏览其中的前 1,200 个条目。
如果有键不是您提供的格式,则遍历它们并首先检查它们是否匹配:
for key in data.keys():
m = re.match('frame(\d+).jpg(\d+)$', key)
if not m: continue
f1, f2 = map(int, m.groups())
if f1<0 or f1>1199 or f2<10000 or f2>99999: continue
x = data[key]['regions']['0']['shape_attributes']['cx']
y = data[key]['regions']['0']['shape_attributes']['cy']
...
推荐阅读
- ios - 使用核心数据时冻结的 UI .mainQueueConcurrencyType
- git - Git:git log 中显示的提交的 SHA 与 PR 中的不同吗?
- c - 在 NASM 中无法正确计算平方根函数
- jenkins - 通过詹金斯作业运行时,如何使 JUnit 测试访问远程服务器文件夹?
- hive - Hive 有睡眠功能吗?
- android - 在 Android 项目中使用 Kotlin + progurad 时出现 ClassCastException
- python - 了解 pandas 合并中的“left_index”和“right_index”参数
- javascript - Laravel ajax 无法正常运行
- python - 合并列具有默认值和覆盖的数据框
- python - 如何格式化 scikit-learn 输出数据?