从批量word文件中提取指定数据存入csv中

需求:

有一批doc格式的文件,并从中提取批量指定内容存入excel中。

首先将doc文件格式转换为docx文件

python 复制代码
#首先得安装pywin32库,此处省略


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:19:24 2020
需要先安装office或者wps,自动将py文件同级文件夹下(含子文件夹)内所有的doc、xls、ppt转成docx/xlsx/pptx
已经是纯py程序,直接在python环境下运行即可,转换完成后会自动删除老版本文件。自己根据需要可调整。doc和xls文件转换时属于静默转换,ppt因为office软件原因,不支持后台静默转换,会跳出ppt软件窗口,但转换完成后会自动关闭。
原理:直接调用office相关API执行打开文件、另存为等操作,因为WPS的API兼容OFFICE,所以安装了WPS后也可以用。
@author: w
"""

import os
import logging
from win32com import client

logging.basicConfig(filename='rz.txt', level=logging.DEBUG, format='%(asctime)s-%(levelname)s-%(message)s')  # 启动日志
logging.debug("程序开始!")


def doc_to_docx(path):
    if os.path.splitext(path)[1] == ".doc":
        word = client.Dispatch('Word.Application')
        doc = word.Documents.Open(path)  # 目标路径下的文件
        doc.SaveAs(os.path.splitext(path)[0] + ".docx", 16)  # 转化后路径下的文件
        doc.Close()
        word.Quit()


def xls_to_xlsx(path):
    if os.path.splitext(path)[1] == ".xls":
        excel = client.Dispatch('Excel.Application')
        xls = excel.Workbooks.Open(path)  # 目标路径下的文件
        xls.SaveAs(os.path.splitext(path)[0] + ".xlsx", 51)  # 转化后路径下的文件
        xls.Close()
        excel.Quit()


def ppt_to_pptx(path):
    if os.path.splitext(path)[1] == ".ppt":
        powerpoint = client.Dispatch('PowerPoint.Application')
        client.gencache.EnsureDispatch('PowerPoint.Application')
        powerpoint.Visible = 1
        ppt = powerpoint.Presentations.Open(path)  # 目标路径下的文件
        ppt.SaveAs(os.path.splitext(path)[0] + ".pptx")  # 转化后路径下的文件
        ppt.Close()
        powerpoint.Quit()


def find_file(path, ext, file_list=[]):
    dir = os.listdir(path)
    for i in dir:
        i = os.path.join(path, i)
        if os.path.isdir(i):
            find_file(i, ext, file_list)
        else:
            if ext == os.path.splitext(i)[1]:
                file_list.append(i)
    return file_list


# 获取当前py文件所在路径
dir_path = os.path.split(os.path.realpath(__file__))[0]
# print(dir_path)
# os._exit()
#dir_path = "D:\我的文档\桌面\附件1文件" #批量转换文件夹

dir_path=r'D:\develop\Python\extract_score\score2'

ext = ".doc"
file_list = find_file(dir_path, ext)
for file in file_list:
    try:
        doc_to_docx(file)
        logging.debug(file)
        os.remove(file)
    except Exception as bcnr:
        logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)
# print(file_list)

ext = ".xls"
file_list = find_file(dir_path, ext)
for file in file_list:
    try:
        xls_to_xlsx(file)
        logging.debug(file)
        os.remove(file)
    except Exception as bcnr:
        logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)

# print(file_list)

ext = ".ppt"
file_list = find_file(dir_path, ext)
for file in file_list:
    try:
        ppt_to_pptx(file)
        logging.debug(file)
        os.remove(file)
    except Exception as bcnr:
        logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)
# print(file_list)

参考地址:自动批量一次性转换工具,doc转docx,xls转xlsx,ppt转pptx,基于python_doc批量转docx-CSDN博客

然后读取docx文件中的指定内容

python 复制代码
import docx
import os
import csv as csv

# 加载Word文档
# doc = docx.Document('a.docx')

# 存储提取的内容
contacts = []

path = "D:\\develop\\Python\\extract_score\\score1\\"

allItems = os.listdir(path)

# 新打开一个 info3.CSV 文件

fo = open("info3.csv", "w", newline='')

# 将表头存储在一个列表中

header = []
cols = 39
for i in range(cols):
    header.append(f"id{i}")

# 创建一个 DictWriter 对象,第二个参数就是上面创建的表头

writer = csv.DictWriter(fo, header)

# 将小刚的记录插入到row_list 中
row_list = []
j = 0
for item in allItems:
    doc = docx.Document(path+item.title())
    # 遍历文档中的段落并提取联系人关键字对应的内容
    for paragraph in doc.paragraphs:
        if '学生姓名:' in paragraph.text:
            # 获取关键字后面的内容
            contact = paragraph.text.split('学生姓名:', 1)[1]
            contacts.append(contact.strip())
        if '实际得分:' in paragraph.text:
            # 获取关键字后面的内容
            contact = paragraph.text.split('实际得分:', 1)[1]
            contacts.append(contact.strip().replace("分", ''))
    # 显示提取的内容
    print(contacts)
    dict = {}
    for i in range(cols):
        print(contact)
        dict[f"id{i}"] = contacts[j+i]
    j += cols
    row_list.append(dict)

# 调用 writerows 方法,一次性写多个字典(一个字典列表)到 CSV 文件中
writer = csv.DictWriter(fo, header)

# 写表头
writer.writeheader()

# 调用 writerows 方法,一次性写多个字典(一个字典列表)到 CSV 文件中

writer.writerows(row_list)


# 关闭文件

fo.close()

参考地址:快乐学Python,使用Python将数据写入CSV文件中_python写csv文件-CSDN博客

相关推荐
别问!问就是全会17 分钟前
Jupyter Notebook 安装包下载|单元格分块运行,图表直接内嵌
ide·python·其他·jupyter
深蓝AI41 分钟前
Python 缓存击穿实测:16 个并发请求如何只回源 1 次
python
benchmark_cc44 分钟前
用 00700.HK 做港股行情清洗:字段核对、校验与个人量化开发实践
python·数据分析·pandas·量化交易·股票数据·quantdash
zh路西法2 小时前
【PACE】面向永磁同步电机PMSM 执行器的参数辨识与能耗感知强化学习 Sim-to-Real
python·cma-es·pmsm·sim-to-real·issac·pace
后台模板学习2 小时前
大模型 Prompt 工程在电商订单系统中的踩坑记录
java·python·prompt
2601_967987372 小时前
如何运行 Python 代码
python·最佳实践·脚本文件·代码运行·交互式环境
WiKiLeaks_successor2 小时前
重构Time库的抽象设计
python·重构
AI源码3 小时前
基于 Python 的短视频用户行为分析系统
开发语言·python
第九序言T3 小时前
数据分析岗 Pandas 面试题 20 道(上):概念与读代码
python·数据分析·pandas·数据处理
Dmz丶3 小时前
前端转 AI 100 天 Day 37:Few-shot 与 CoT——让模型学会“推理”
python