python读取word详解【from docx import Document】

简介: python读取word详解【from docx import Document】

前言

       我们平时工作的时候会有很多的时候会遇到需要将word里面的有些杂乱的数据格式化到Excel中去,但是如果手动操作那真是【超级无语】,很崩溃,几百页的word让你慢慢复制粘贴,会死掉的。所以我们需要使用程序来完成,使用python先通过【docx】的包将word中的文字逐行读取出来,再根据行的数据格式进行数据清洗,清洗成对应的列表数据,批量写入Excel即可,这里我写入的是【CSV】文件,也可以通过Excel直接打开的。


环境

系统:win10


工具:PyCharm Community Edition 2021.3.1


解析目标类型:*.docx文件


输出目标类型:*.csv文件


需要用包:pip install docx


使用技巧:字符串处理


示例字符串

1、( A )不可存放于码头普通仓库内。


A、爆炸品          B、棉料              C、煤粉


2、( A )负责核发危险化学品及其包装物、容器生产企业的工业产品生产许可证,并依法对其产品质量实施监督,负责对进出口危险化学品及其包装实施检验。


A、质量监督检验检疫部门     B、安全生产监督局      C、公安部门


3、( A )告诉我们,构成管理系统的各要素是运动和发展的,它们相互联系又相互制约。在生产经营单位建立、健全安全生产责任制是对这一原则的应用。


A、动力相关性原则      B、动力原则        C、人本原理


4、( A )即根据演练工作需要,采取必要安全防护措施,确保参演、观摩等人员以及生产运行系统安全。


A、演练工作安全保障            B、安全防护措施         C、系统安全


5、( A )建立健全应急物资储备保障制度,完善重要应急物资的监管、生产、储备、调拨和紧急配送体系。


A、国家              B、社会               C、企业


下载环境

pip install docx


导入环境

from docx import Document

import csv

import uuid


import re


Document读取word

from docx import Document
import csv
import uuid
import re
file = Document("word.docx")
print(file)

输出对象查看是否读取成功,可以看到有对象的输出,代表读取成功。


image.png


使用【paragraphs】获取段落信息,可以看出输出的文字。

image.png



行拆分

拆分题目行与选择行

from docx import Document
import csv
import uuid
import re
file = Document("word.docx")
# 拆分依据
info = r"( A )|( B )|( C )|(  )"
# 输出样式
header_list2 = ["题型", "难度", "题目问题", "正确答案", "选项A", "选项B", "选项C"]
# 获取file的段落对象
for item in file.paragraphs:
    # 正则区分行
    te = re.search(info, item.text)
    print(te)

测试输出效果:


image.png


信息分析

正则判断根据答案进行判断的,如果这个行有就能输出,如果没有也就是选项那么就会输出【None】,所以我们判断一下是否等于【None】来区分题目行与选项行。


数据分组

from docx import Document
import csv
import uuid
import re
file = Document("word.docx")
# 拆分依据
info = r"( A )|( B )|( C )|(  )"
# 输出样式
header_list2 = ["题型", "难度", "题目问题", "正确答案", "选项A", "选项B", "选项C"]
# 用于最终存储
data_list = []
# 用于存储集合·前两项固定的可以直接写上·我们主要拆分后面5列
list_child = ["单选", "1", "", "", "", "", ""]
# 获取file的段落对象
for item in file.paragraphs:
    # 正则区分行
    te = re.search(info, item.text)
    if te != None:
        if list_child[2] != "":
            data_list.append(list_child)
        list_child = ["单选", "1", "", "", "", "", ""]
        list_child[2] = item.text.replace(item.text[te.span()[0]:te.span()[1]], "(   )")
        list_child[3] = item.text[te.span()[0]:te.span()[1]]
    else:
        item2Len = []
        for item2 in item.text.split(" "):
            if item2 != "":
                item2Len.append(item2)
        list_child[4] = item2Len[0]
        list_child[5] = item2Len[1]
        list_child[6] = item2Len[2]
print(data_list)


分组效果:


image.png


csv文件写入

直接创建一个新的文件写入即可。


from docx import Document
import csv
import uuid
import re
file = Document("word.docx")
# 拆分依据
info = r"( A )|( B )|( C )|(  )"
# 输出样式
header_list2 = ["题型", "难度", "题目问题", "正确答案", "选项A", "选项B", "选项C"]
# 用于最终存储
data_list = []
# 用于存储集合·前两项固定的可以直接写上·我们主要拆分后面5列
list_child = ["单选", "1", "", "", "", "", ""]
# 获取file的段落对象
for item in file.paragraphs:
    # 正则区分行
    te = re.search(info, item.text)
    if te != None:
        if list_child[2] != "":
            data_list.append(list_child)
        list_child = ["单选", "1", "", "", "", "", ""]
        list_child[2] = item.text.replace(item.text[te.span()[0]:te.span()[1]], "(   )")
        list_child[3] = item.text[te.span()[0]:te.span()[1]]
    else:
        item2Len = []
        for item2 in item.text.split(" "):
            if item2 != "":
                item2Len.append(item2)
        list_child[4] = item2Len[0]
        list_child[5] = item2Len[1]
        list_child[6] = item2Len[2]
fileName = "{0}.csv".format(uuid.uuid4())
with open(fileName, 'w', encoding="utf-8-sig", newline="") as csvFile:
    wr = csv.writer(csvFile)
    wr.writerow(header_list2)
    wr.writerows(data_list)

写入效果:



image.png

PyCharm打开效果:


image.png

Excel打开效果:

image.png


演示完毕,根据实际需求处理数据即可。

相关文章
|
1月前
|
数据采集 机器学习/深度学习 Python
【Python】已完美解决:ImportError: cannot import name ‘Imputer‘ from ‘sklearn.preprocessing
【Python】已完美解决:ImportError: cannot import name ‘Imputer‘ from ‘sklearn.preprocessing
68 3
|
6天前
|
Linux Python Windows
Python PDF文件转Word格式,只需要3秒(附打包)
Python PDF文件转Word格式,只需要3秒(附打包)
25 3
Python PDF文件转Word格式,只需要3秒(附打包)
|
3天前
|
XML 存储 数据格式
使用Python的zipfile模块巧解Word批量生成问题
通过以上步骤,我们得到了填充了特定数据的 Word 文档。这个过程可以通过循环对多个数据集重复执行,从而实现批量生成多个 Word 文档的目标。
11 5
|
5天前
|
Python
Python——将PPT和Word转为PDF文件
Python——将PPT和Word转为PDF文件
20 1
|
2月前
|
XML 数据格式 Python
Python的`import`用于加载模块,基础形式是`import module`,全量导入
【6月更文挑战第23天】Python的`import`用于加载模块,基础形式是`import module`,全量导入;`from module import name`选择性导入部分,减少命名空间污染;`from module import *`导入所有(不推荐),易引发冲突。别名导入如`from math import sqrt as square_root`可避免冲突。包导入用`.`,如`import xml.etree.ElementTree as ET`。
44 8
|
2月前
|
XML 数据格式 Python
在Python中,导入其他模块是通过使用import语句完成的
在Python中导入模块涉及`import`语句的不同用法:1) `import math`导入整个标准库;2) `from math import sqrt`导入单个函数;3) `import numpy as np`使用别名;4) `from random import *`导入所有(不推荐);5) `import xml.etree.ElementTree as ET`导入子模块;6) 使用`importlib.import_module()`延迟导入;7) `from .module import func`导入相对路径模块,需管理`sys.path`。
43 6
|
1月前
|
XML API 数据格式
【Python】 已解决:ValueError: document with multiple roots
【Python】 已解决:ValueError: document with multiple roots
20 0
|
1月前
|
Python
【Python】已解决:(from docx import Document导包报错)ModuleNotFoundError: No module named ‘exceptions’
【Python】已解决:(from docx import Document导包报错)ModuleNotFoundError: No module named ‘exceptions’
36 0
|
1月前
|
XML JavaScript 数据格式
【Python】已解决:(Python xml库 import xml.dom.minidom导包报错)‘No module named dom’
【Python】已解决:(Python xml库 import xml.dom.minidom导包报错)‘No module named dom’
32 0
|
2月前
|
Python
Python中import的机制详解
Python中import的机制详解
19 0