首页 > 解决方案 > 如何从列中获取属性高度、宽度、x 和 y?

问题描述

我们有 1000 行具有相同信息的 CSV 文件存储在一列中,如下所示。我们如何循环它并在 python 中获取属性 x、y、height 和 width?

[{"task":"T0","task_label":"Draw a box around each person name and transcribe their information.","value":[{"x":224.63333129882812,"y":89.96666717529297,"tool":0,"frame":0,"width":333.9999694824219,"height":42.00000762939453,"details":[{"value":"Rev. Leopold Wyke Acland"},{"value":0}],"tool_label":"Tool name"},{"x":95.63333129882812,"y":55.96666717529297,"tool":0,"frame":0,"width":280,"height":37,"details":[{"value":"Acland, Thomas Wyke"},{"value":0}],"tool_label":"Tool name"}]}]

标签: pythonpandascsv

解决方案


由于最外层list仅包含一个具有 3 个字段的对象

  1. task不需要。
  2. task_label不需要。
  3. value我们感兴趣的一个。

在给定的上下文中,我们可以通过dict以下方式循环

for item in data[0]["value"]:
    print(f"x = {item['x']}")
    print(f"y = {item['y']}")
    print(f"width = {item['width']}")
    print(f"height = {item['height']}")

您还可以以更 Python 的方式收集这些值,然后遍历结果的字典列表

result = [
            {
                "x": item["x"], 
                "y": item["y"], 
                "width": item["width"], 
                "height": item["height"]
             } 
          for item in data[0]["value"]]

我建议在 python 中进行迭代。此外,此代码段假定所有行都具有统一的结构

https://wiki.python.org/moin/ForLoop


推荐阅读