python读取json数据

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python读取json数据

kuokay   2022-05-23 我要评论

背景:

由于需要对ocr识别系统的表格识别结果做验证,通过返回的json文件结果对比比较麻烦,故需要将json文件里面的识别结果还原为表格做验证。

文件部分内容如下:

{"row":"6","col","5""start_row": 0, "start_column": 0, "end_row": 0, "end_column": 0, "data": "称", "position": [51, 71, 168, 93], "org_position": [50, 60, 167, 62, 166, 84, 49, 82], "char_position": [[86, 83, 100, 100]], "lines": [{"text": "称", "poly": [84, 73, 98, 73, 98, 90, 84, 90, 0.874], "score": 0.874, "char_centers": [[91, 82]], "char_polygons": [[84, 77, 98, 74, 98, 87, 84, 90]], "char_candidates": [["称"]], "char_candidates_score": [[0.999]], "char_scores": [0.999]}]}

现在需要通过行列的起始和结束坐标以及内容生成相应的表格

开始准备使用js但由于一些语法忘记,所以还是选用python进行。
在经过一些列研究后发现利用python-docx可自动生成表格,但是格式是word的,所有后期又进行了word转html操作。

一、实操

pip install python_docx

1.首先创建一个新的文档

from docx import Document
document = Document()

然后用Document类的add_table方法增加一个表格,其中rows是行,cols是列,style表格样式,具体可以查看官方文档:

table = document.add_table(rows=37,cols=13,style='Table Grid')

上述代码就在word里插入了一个37行、13列的表格。(有37*13=481个cell)

生成的每个cell都是有“坐标”的,比如上面的表格左上角cell为(0,0),右下角cell为(36,12)

下面要做的就是合并一些cell,从而达到我们最终需要的表格

table.cell(0,0).merge(table.cell(2,2))

上述代码就将cell(0,0)到cell(2,2)之间的所有cell合并成一个cell

这里需要注意的是,虽然每个cell都合并了,但其实它还是存在的。比如合并了(0,0)和(0,1)两个cell,那么这个合并的cell其实就是(0,0;0,1)

如果cell较多,无法直观的看出坐标的话,可以用下列的代码将每个cell的坐标都标注出来,方便合并

document = Document()
table = document.add_table(rows=37,cols=13,style='Table Grid')

document.save('table-1.docx')

document1 = Document('table-1.docx')
table = document1.tables[0]
for row,obj_row in enumerate(table.rows):
   for col,cell in enumerate(obj_row.cells):
       cell.text = cell.text + "%d,%d " % (row,col)

document1.save('table-2.docx')

2.添加文本

将所有cell依次合并后,就需要向合并后的cell里添加文本。

用table的row方法可以得到一个表格的一行list其中包含了这一行的所有cell

hdr_cells0 = table.rows[0].cells

上面代码就得到了合并表格后的第一行所有cell,然后我们用hdr_cell0[0]就可以得到合并表格后的第一行的第一个cell。用add_paragraph方法即可像cell里添加文本

hdr_cells0[0].add_paragraph('数据文字')

其他使用方法可参考官网模块:https://www.osgeo.cn/python-docx/

二、word转成html

1.使用pydocx转换

pip install pydocx

from pydocx import PyDocX
html = PyDocX.to_html("test.docx")
f = open("test.html", 'w', encoding="utf-8")
f.write(html)
f.close()

通过网页上传word文档,只接收docx

<form method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document">
</form>

2.使用win32模块

pip3 install pypiwin32

from win32com import client as wc
import os

word = wc.Dispatch('Word.Application')


def wordsToHtml(dir):
    for path, subdirs, files in os.walk(dir):
        for wordFile in files:
            wordFullName = os.path.join(path, wordFile)
            doc = word.Documents.Open(wordFullName)

            wordFile2 = wordFile
            dotIndex = wordFile2.rfind(".")
            if (dotIndex == -1):
                print(wordFullName + "********************ERROR: 未取得后缀名!")

            fileSuffix = wordFile2[(dotIndex + 1):]
            if (fileSuffix == "doc" or fileSuffix == "docx"):
                fileName = wordFile2[: dotIndex]
                htmlName = fileName + ".html"
                htmlFullName = os.path.join(path, htmlName)
                print("generate html:" + htmlFullName)
                doc.SaveAs(htmlFullName, 10)
                doc.Close()

    word.Quit()
    print("")
    print("Finished!")


if __name__ == '__main__':
    import sys

    if len(sys.argv) != 2:
        print("Usage: python funcName.py rootdir")
        sys.exit(100)
    wordsToHtml(sys.argv[1])

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们