根据每个表的 x 和 y 坐标为每个表指定一个行值

  • 本文关键字:一个 坐标 python dictionary
  • 更新时间 :
  • 英文 :


我试图根据x轴给字典中的每个table_row字段一个字母,根据y轴给每个table_number字段一个数字。

我的JSON文件如下所示:

{
"table": [
[
{
"table_row": "",
"table_number": 0,
"table_serial": "",
"xmax": 640.0,
"ymax": 418.1505432129,
"xmin": 142.3304901123,
"ymin": 93.9450378418
},
{
"table_row": "",
"table_number": 0,
"table_serial": "",
"xmax": 640.0,
"ymax": 418.2640991211,
"xmin": 156.3077545166,
"ymin": 91.5001678467
}]}

这是我迄今为止写的代码,但我想不出一个好的方法:

with open("orderddata.json", "r+") as m:
js.dump(l, m, indent=2)
list_row = string.ascii_uppercase
for table in dict["table"]:
temp = table["position"]["xmax"]
for i in len(dict["table"]):
if table["position"]["xmax"] >= temp :
temp = table["position"]["xmax"]
table["row"] = list_row[i:1]
for table in dict["table"]:
temp = table["position"]["ymax"]
for i in len(dict["table"]):
if table["position"]["ymax"] >= temp :
temp = table["position"]["ymax"]
table["table_number"] = i

预期结果是:

{
"table": [
[
{
"table_row": "A",
"table_number":2 ,
"table_serial": "",
"xmax": 640.0,
"ymax": 500.1505432129,
"xmin": 142.3304901123,
"ymin": 93.9450378418
},
{
"table_row": "A",
"table_number": 1,
"table_serial": "",
"xmax": 640.0,
"ymax": 300.2640991211,
"xmin": 156.3077545166,
"ymin": 91.5001678467
}]}

目前尚不清楚您要做什么,但根据您的代码片段和(格式不好的(JSON示例,这里有一个可能的解决方案:

import json
from string import ascii_uppercase
json_string = '''
{
"table": [[
{
"table_row": "",
"table_number": "",
"table_serial": "",
"xmax": 640.0,
"ymax": 418.1505432129,
"xmin": 142.3304901123,
"ymin": 93.9450378418
},
{
"table_row": "",
"table_number": "",
"table_serial": "",
"xmax": 640.0,
"ymax": 418.2640991211,
"xmin": 156.3077545166,
"ymin": 91.5001678467
}
]]
}'''
tables = json.loads(json_string)
xmax = 0
ymax = 0
for i, table in enumerate(tables['table']):
for j, row in enumerate(table):
# find max(xmax)
if row['xmax'] > xmax:
xmax = row['xmax']
# find max(ymax)
if row['ymax'] > ymax:
ymax = row['ymax']
# fill row and table_number
tables['table'][i][j]['table_row'] = ascii_uppercase[i]
tables['table'][i][j]['table_number'] = j + 1
print('xmax:', xmax)
print('ymax:', ymax)
print(json.dumps(tables, indent=2))

上面的代码将输出以下内容:

xmax: 640.0
ymax: 418.2640991211
{
"table": [
[
{
"table_row": "A",
"table_number": 1,
"table_serial": "",
"xmax": 640.0,
"ymax": 418.1505432129,
"xmin": 142.3304901123,
"ymin": 93.9450378418
},
{
"table_row": "A",
"table_number": 2,
"table_serial": "",
"xmax": 640.0,
"ymax": 418.2640991211,
"xmin": 156.3077545166,
"ymin": 91.5001678467
}
]
]
}

但请记住,如果table列表的行数多于len(ascii_uppercase),则上面的代码将失败。你没有告诉我们在这种情况下该怎么办。

最新更新