任務(wù)要求:
將每頁需要的內(nèi)容讀取出來放到不同的文件夾,找出含有指定內(nèi)容的頁面創(chuàng)建文件夾,然后把相關(guān)的內(nèi)容和圖片放進去。文章來源:http://www.zghlxwxcb.cn/news/detail-653455.html
一 先將word轉(zhuǎn)為PDF
pdf 讀起來比較方便, 按頁碼讀取文件:文章來源地址http://www.zghlxwxcb.cn/news/detail-653455.html
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):
"""
根據(jù)編號創(chuàng)建文件夾
: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'編號名稱存在不能使用的字符,需要單獨調(diào)整,Page {count}, 編號后面的內(nèi)容: {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"]
# 從流中提取圖像數(shù)據(jù)
img_data = img_stream.get_data()
# 使用數(shù)據(jù)創(chuàng)建新圖像
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 需要先將文檔轉(zhuǎn)換為 pdf
2 文件夾名稱不要頁碼改 39 行
3 編號最好不要出現(xiàn) * 這種不能作為文件名的符號
4 filePath 改文件路徑
5 保存文件在同級文件目錄下
"""
# filePath = r"E:\11-normal_program\registration_card.pdf"
filePath = r"./registration_card.pdf"
CountPages(filePath)
到了這里,關(guān)于python讀取word/pdf文檔,指定文字內(nèi)容和圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!