说说 python-docx 解析 word 文档的原理

Python015

说说 python-docx 解析 word 文档的原理,第1张

首先通过 pip 安装 python-docx,命令为 pip install python-docx 。

python-docx 使用 Document 对象来表示整个 docx 文档。其内部包含 一个Paragraph 对象列表。每个 Paragraph 对应 docx 文档的一个段落。

word 文档中除了字符串,还包含字体、大小、颜色等样式信息。相同样式的连续字符串,就会被保存在一个 Run 对象中。

假设 docx 文档中有下面这些内容:

那么经过 python-docx 解析,就会生成 3 个 Run 对象:

# -*- coding:gb2312 -*-

import json

def read_txt_high(filename):

    with open(filename, 'r') as file_to_read:

        list0 = [] #文件中的第一列数据

        list1 = [] #文件中的第二列数据

        while True:

            lines = file_to_read.readline()  # 整行读取数据

            if not lines:

                break

            item = [i for i in lines.split()]

            data0 = json.loads(item[0])#每行第一个值

            data1 = json.loads(item[1])#每行第二个值

            list0.append(data0)

            list1.append(data1)

    return list0,list1