[英]Convert string dict type to dict
我正在尝试使用 python 将数据帧的列转换为 dict。
dataframe 的形式为
filename bbox-coordinates
image_name1 '{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}'
image_name2 '{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}'
image_name3 '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'
bbox 坐标值是字符串类型,我正在尝试将其转换为 dict。
dataframe['bbox-coordinate'][2]
output: '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}' which is string
这里:
[1] type(dataframe['region_shape_attributes'][0])
output: str
我尝试使用:
ast.literal_eval --- doesn't work
json.loads(dataframe['bbox-coordinate'][2])
output: JSONDecodeError: Expecting ':' delimiter: line 1 column 4 (char 3)
我的最终目标是将整个 dataframe 转换为带有图像 class 名称的 YOLO format.txt,这只有一个 class 即 0,并以 Y_O 格式提取每个文件的高度 x、宽度和宽度。
出于某种原因,您的字符串中似乎有双双引号( ""
)。 只需用单个双引号( "
)替换它们, ast.literal_eval()
就可以了。
from ast import literal_eval
strings = [
'{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}',
'{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}',
'{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'
]
dicts = []
for s in strings:
d = literal_eval(s.replace('""', '"'))
dicts.append(d)
print(dicts)
返回
[{'name': 'rect', 'x': 161, 'y': 562, 'width': 51, 'height': 96},
{'name': 'rect', 'x': 151, 'y': 542, 'width': 32, 'height': 69},
{'name': 'rect', 'x': 140, 'y': 42, 'width': 30, 'height': 45}]
我找到了使用 json 的解决方案
import json
strigDicts = [
'{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}',
'{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}',
'{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'
]
dicts = []
for d in strigDicts:
dicts.append(json.loads(d.replace('""', '"')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.