数据分析进阶-Python提取Word文档中的表格信息

前言

利用此方法针对大量的报名表进行信息提取~

安装工具包

pip install python-docx

表格信息

在这里插入图片描述

代码

注意读取的EXCEL文件只能是docx后缀的噢~若文件太多可利用以下方法批量转化

import os
import docx
import xlwt
import shutil
from win32com import client as wc

# 把doc文档转成docx文档
def convert_word(path, target_dir):
    filename = os.path.basename(path)
    rename = os.path.splitext(filename)
    new_file = target_dir + '/' + rename[0] + '.docx'
    source_path = os.path.abspath(path)
    target_path = os.path.abspath(new_file)
    word = wc.Dispatch('Word.Application')
    doc = word.Documents.Open(source_path)
    doc.SaveAs(target_path, 12)
    doc.Close()
    word.Quit()
表格信息提取
doc = docx.Document('报名表.docx')
tables = doc.tables
fields = [
        '姓名',
        '性别',
        '专业',
        '班级',
        '联系电话',
        '电子邮箱'
    ]
    
for table in tables:
    table_data = dict()
    for key in fields:
        table_data[key] = ''
        for row in table.rows:
            tmp_last = ''
            for cell in row.cells:
                text = cell.text.strip()
                if text == tmp_last:
                    continue
                if tmp_last in fields:
                    table_data[tmp_last] = text
                tmp_last = text.replace(' ', '')
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值