[英]Convert string dict type to dict
I am trying to convert a column of the data frame to dict using python.我正在尝试使用 python 将数据帧的列转换为 dict。
The dataframe is of the form 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}'
the bbox-coordinate value is of type string and I am trying to convert it to dict. bbox 坐标值是字符串类型,我正在尝试将其转换为 dict。
dataframe['bbox-coordinate'][2]
output: '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}' which is string
Here:这里:
[1] type(dataframe['region_shape_attributes'][0])
output: str
I tried using:我尝试使用:
ast.literal_eval --- doesn't work
json.loads(dataframe['bbox-coordinate'][2])
output: JSONDecodeError: Expecting ':' delimiter: line 1 column 4 (char 3)
My ultimate goal is to convert the entire dataframe into YOLO format.txt with image class name, this has only one class ie 0 and to extract the x, y, height and width in the YOLO.txt format for each file_name.我的最终目标是将整个 dataframe 转换为带有图像 class 名称的 YOLO format.txt,这只有一个 class 即 0,并以 Y_O 格式提取每个文件的高度 x、宽度和宽度。
For some reason, it seems like your strings have double double-quotes in them ( ""
).出于某种原因,您的字符串中似乎有双双引号(
""
)。 Just replace them with single double-quotes ( "
) and ast.literal_eval()
will work just fine.只需用单个双引号(
"
)替换它们, 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)
returns返回
[{'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}]
I found a solution using json我找到了使用 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.