[英]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.