首页 > 解决方案 > 在python中使用height、left、top、width来格式化excel表格

问题描述

我遇到了一个奇怪的 JSON 响应,需要将其保存到 excel 中,我尝试了 pandas,但它不能以预期的方式工作(或者我使用不正确,我是 python 新手),现在我正在尝试用来xlwt格式化它,但params我得到的唯一JSON回应是“高度,左侧,顶部,宽度”:

例如: {'rect': {'angle': -90, 'height': 12, 'left': 31, 'top': 22, 'width': 12}, 'word': 'A'}, {'rect': {'angle': -90, 'height': 12, 'left': 301, 'top': 23, 'width': 14}, 'word': 'B'}, {'rect': {'angle': -90, 'height': 11, 'left': 698, 'top': 25, 'width': 11}, 'word': 'D'}, {'rect': {'angle': -90, 'height': 10, 'left': 829, 'top': 25, 'width': 12}, 'word': 'E'}, {'rect': {'angle': -90, 'height': 11, 'left': 909, 'top': 23, 'width': 14}, 'word': 'F'}, {'rect': {'angle': -90, 'height': 12, 'left': 993, 'top': 24, 'width': 13}, 'word': 'G'}, {'rect': {'angle': -90, 'height': 12, 'left': 1076, 'top': 24, 'width': 12}, 'word': 'H'}........还有更多的行

我不能只遍历它,因为如果我这样做,它不会开始新的一行。

请告诉我如何利用“高度、左侧、顶部、宽度”。

标签: pythonjsonexcelxlwt

解决方案


这是一个普通的 json 响应,但它是一个嵌套响应,因此很难直接加载到 pandas 中。在下面的解决方案中,我假设您已将json 响应加载为名为“数据”的 python 字典列表。

import pandas as pd

data = [{'rect': {'angle': -90, 'height': 12, 'left': 31, 'top': 22, 'width': 12}, 'word': 'A'}, {'rect': {'angle': -90, 'height': 12, 'left': 301, 'top': 23, 'width': 14}, 'word': 'B'}, {'rect': {'angle': -90, 'height': 11, 'left': 698, 'top': 25, 'width': 11}, 'word': 'D'}, {'rect': {'angle': -90, 'height': 10, 'left': 829, 'top': 25, 'width': 12}, 'word': 'E'}, {'rect': {'angle': -90, 'height': 11, 'left': 909, 'top': 23, 'width': 14}, 'word': 'F'}, {'rect': {'angle': -90, 'height': 12, 'left': 993, 'top': 24, 'width': 13}, 'word': 'G'}, {'rect': {'angle': -90, 'height': 12, 'left': 1076, 'top': 24, 'width': 12}, 'word': 'H'}]

#assuming you wish to include the word variable in a column as well, let's add it to the 'rect' key so we can load the rect keys into a pandas dataframe
for i in data:
  i['rect']['word'] = i['word']

#we need to create a list that only contains the data from the rect keys, otherwise pandas can't load it. So let's use list comprehension
df=pd.DataFrame([i['rect'] for i in data])
df.to_excel('output.xlsx')

输出:

    angle   height  left    top width   word
0   -90     12      31      22  12      A
1   -90     12      301     23  14      B
2   -90     11      698     25  11      D
3   -90     10      829     25  12      E
4   -90     11      909     23  14      F

推荐阅读