python - 在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'}
........还有更多的行
我不能只遍历它,因为如果我这样做,它不会开始新的一行。
请告诉我如何利用“高度、左侧、顶部、宽度”。
解决方案
这是一个普通的 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
推荐阅读
- android - 为什么我不能在 Kotlin 中使用 Class 类型作为泛型参数?
- angular - 使用 formControlName 的下拉垫选择的初始值未反映在 UI 中
- xamarin.forms - Xamarin 表单地图上的透明圆圈覆盖不可点击(仅限 IOS)
- azure - 将数据从数据库移动到 Azure Blob 存储
- sql - 材料清单
- amazon-web-services - 有谁知道 ELB 需要多长时间才能扩展?
- python - 在点 matplotlib 上方添加注释
- c# - 将 LINQ 结果发送到 ASP.NET MVC 中的另一个函数
- css - Sass 和附加父类
- docker - 为 Visual Studio Docker-Compose 项目设置启动 URL