python读取word/pdf文档,逐页读取-指定文字内容和图片

任务要求:

将每页需要的内容读取出来放到不同的文件夹,找出含有指定内容的页面创建文件夹,然后把相关的内容和图片放进去。


一 先将word转为PDF

pdf 读起来比较方便, 按页码读取文件:

import pdfplumber
from PIL import Image
import cv2
import numpy as np
import re
import os
import logging
import io


def create_folder(folder_name):
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)


def CountPages(file_path):
    """
    根据编号创建文件夹
    :param file_path:
    :return:
    """
    with pdfplumber.open(file_path) as pdf:
        count = 0
        for page in pdf.pages:
            count += 1
            print(f"----------- 第{count}页 ----------- \n\n")

            text = page.extract_text()
            matches = re.findall(r'编号\s*(\S+)', text)

            if matches:
                for match in matches:
                    if '*' in match:
                        logging.warning(f'编号名称存在不能使用的字符,需要单独调整,Page {count}, 编号后面的内容: {match}')
                        folder_name = 'new_files/' + f'000 error Page_{count}'
                        # continue
                    else:
                        # folder_name = './new_files/' + match
                        folder_name = './new_files/' + f'{count}_' + match
                    create_folder(folder_name)

            images = page.images
            print(f'images: {images}')
            for i, img in enumerate(images):
                # x0, y0, x1, y1 = img["x0"], img["y0"], img["x1"], img["y1"]
                img_stream = img["stream"]

                # 从流中提取图像数据
                img_data = img_stream.get_data()

                # 使用数据创建新图像
                pil_img = Image.open(io.BytesIO(img_data))

                # 将图像保存为 JPG
                img_filename = f"{folder_name}/image_{count}_{i + 1}.jpg"
                pil_img.save(img_filename, format="JPEG")
                print(f"保存图像:{img_filename}")

        return count


"""
    1 需要先将文档转换为 pdf
    2 文件夹名称不要页码改 39 行
    3 编号最好不要出现 * 这种不能作为文件名的符号
    4 filePath 改文件路径
    5 保存文件在同级文件目录下
"""

# filePath = r"E:\11-normal_program\registration_card.pdf"
filePath = r"./registration_card.pdf"
CountPages(filePath)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值