关键词搜索

源码搜索 ×
×

如何用Python将Word文档转换为Excel表格

发布2021-01-16浏览817次

详情内容

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。

作者:小小明

来源:菜J学Python

Python爬虫、数据分析、网站开发等python基础教程案例教程视频免费在线观看
https://www.xin3721.com/eschool/pythonxin3721/

需求
有一个下面这种形式的word表格:
在这里插入图片描述

如何用Python将Word文档转换为Excel表格

希望能转换为下面这种格式的excel表格:
在这里插入图片描述

如何用Python将Word文档转换为Excel表格

测试word文档读取
先测试一个word文档前1页的数据读取:

from docx import Document

doc = Document(“编号02 质检员高级技师(一级)理论试卷.docx”)
for i, paragraph in enumerate(doc.paragraphs[:55]):
print(i, paragraph.text)
如何用Python将Word文档转换为Excel表格
在这里插入图片描述

从读取效果上看,各行文本数据都能很顺利的获取到。

匹配题型、题目和具体的选项
现在我们需要做的是就是匹配题型、题目和具体的选项,观察可以发现规律:

题型以大写数字开头
题目以普通数字+.开头
选项以括号+字母开头

额外需要注意的:

开头几行文本也存在普通数字+.开头的,需要直接排除。

第7题的题目,和第19题的选项存在一些特殊的空白字符需要排除,

括号和小数点都同时存在半角和全角两种情况。

对于需要注意的第二点:

在这里插入图片描述
如何用Python将Word文档转换为Excel表格
查看一下这2处的空白字符:

doc.paragraphs[21].text
‘7.(\xa0\xa0)是第一家实施六西格玛管理的公司。\xa0’

doc.paragraphs[49].text
‘(A)参数设计 (B)常量设计\u3000 (C)变量设计\u3000\u3000 (D)系统设计’

发现分别是\xa0和\u3000。

整理好大致思路,我组织一下处理代码:

import re
from docx import Document

doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")

black_char = re.compile("[\s\u3000\xa0]+")

chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
title_rule = re.compile("\d+.")
option_rule = re.compile("\([ABCDEF]\)")
option_rule_search = re.compile("\([ABCDEF]\)[^(]+")


# 从word文档的“一、单项选择题”开始遍历数据
for paragraph in doc.paragraphs[5:25]:
    #  去除空白字符,将全角字符转半角字符,并给括号之间调整为中间二个空格
    line = black_char.sub("", paragraph.text).replace(
        "(", "(").replace(")", ")").replace(".", ".").replace("()", "(  )")
    # 对于空白行就直接跳过
    ifnot line:
        continue
    if title_rule.match(line):
        print("题目", line)
    elif option_rule.match(line):
        print("选项", option_rule_search.findall(line))
    else:
        chinese_nums_match = chinese_nums_rule.match(line)
        if chinese_nums_match:
            print("题型", chinese_nums_match.group(1))

    在这里插入图片描述

    如何用Python将Word文档转换为Excel表格
    从目前测试结果来看没有问题。

    保存匹配到的数据到结构化字典
    现在我打算将当前匹配出来的文本数据存储成字典形式的结构化数据,字典结构的设计如下:

    如何用Python将Word文档转换为Excel表格
    在这里插入图片描述

    根据上述设计完善代码:

    import re
    from docx import Document
    from collections import OrderedDict
    
    doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
    
    black_char = re.compile("[\s\u3000\xa0]+")
    
    chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
    title_rule = re.compile("\d+.")
    option_rule = re.compile("\([ABCDEF]\)")
    option_rule_search = re.compile("\([ABCDEF]\)[^(]+")
    
    # 保存最终的结构化数据
    question_type2data = OrderedDict()
    # 从word文档的“一、单项选择题”开始遍历数据
    for paragraph in doc.paragraphs[5:]:
        #  去除空白字符,将全角字符转半角字符,并给括号之间调整为中间一个空格
        line = black_char.sub("", paragraph.text).replace(
            "(", "(").replace(")", ")").replace(".", ".").replace("()", "(  )")
        # 对于空白行就直接跳过
        ifnot line:
            continue
        if title_rule.match(line):
            options = title2options.setdefault(line, [])
        elif option_rule.match(line):
            options.extend(option_rule_search.findall(line))
        else:
            chinese_nums_match = chinese_nums_rule.match(line)
            if chinese_nums_match:
                question_type = chinese_nums_match.group(1)
                title2options = question_type2data.setdefault(question_type, OrderedDict())
    
      30
    • 31
    • 32

    遍历结构化字典并存储
    然后我们遍历结构化字典,将数据保存到pandas对象中:

    import pandas as pd
    
    result = []
    max_options_len = 0
    for question_type, title2options in question_type2data.items():
        for title, options in title2options.items():
            result.append([question_type, title, *options])
            options_len = len(options)
            if options_len > max_options_len:
                max_options_len = options_len
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    结果:
    在这里插入图片描述

    如何用Python将Word文档转换为Excel表格

    最终保存结果:

    df.to_excel(“result.xlsx”, index=False)
    完整代码
    最终完整代码:

    import pandas as pd
    import re
    from docx import Document
    from collections import OrderedDict
    
    doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
    
    black_char = re.compile("[\s\u3000\xa0]+")
    
    chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
    title_rule = re.compile("\d+.")
    option_rule = re.compile("\([ABCDEF]\)")
    option_rule_search = re.compile("\([ABCDEF]\)[^(]+")
    
    # 保存最终的结构化数据
    question_type2data = OrderedDict()
    # 从word文档的“一、单项选择题”开始遍历数据
    for paragraph in doc.paragraphs[5:]:
        #  去除空白字符,将全角字符转半角字符,并给括号之间调整为中间一个空格
        line = black_char.sub("", paragraph.text).replace(
            "(", "(").replace(")", ")").replace(".", ".").replace("()", "(  )")
        # 对于空白行就直接跳过
        ifnot line:
            continue
        if title_rule.match(line):
            options = title2options.setdefault(line, [])
        elif option_rule.match(line):
            options.extend(option_rule_search.findall(line))
        else:
            chinese_nums_match = chinese_nums_rule.match(line)
            if chinese_nums_match:
                question_type = chinese_nums_match.group(1)
                title2options = question_type2data.setdefault(
                    question_type, OrderedDict())
    
    result = []
    max_options_len = 0
    for question_type, title2options in question_type2data.items():
        for title, options in title2options.items():
            result.append([question_type, title, *options])
            options_len = len(options)
            if options_len > max_options_len:
                max_options_len = options_len
    df = pd.DataFrame(result, columns=[
                      "题型", "题目"]+[f"选项{i}"for i in range(1, max_options_len+1)])
    # 题型可以简化下,去掉选择两个字
    df['题型'] = df['题型'].str.replace("选择", "")
    df.to_excel("result.xlsx", index=False)
    
      30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    最终得到的文件:

    如何用Python将Word文档转在这里插入图片描述
    换为Excel表格

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载