【问题标题】:using height, left, top, width to format a excel table in python在python中使用height、left、top、width来格式化excel表格
【发布时间】:2021-04-22 07:26:44
【问题描述】:

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

例如: {'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'}........还有更多行

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

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

【问题讨论】:

    标签: python json excel xlwt


    【解决方案1】:

    这是一个普通的 json 响应,但它是一个嵌套响应,这使得直接加载到 pandas 中变得困难。在下面的解决方案中,我假设您有 loaded the json response 作为名为“数据”的字典的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      相关资源
      最近更新 更多