当前位置:   article > 正文

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

pycharm读取word文档

任务要求:

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


一 先将word转为PDF

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

  1. import pdfplumber
  2. from PIL import Image
  3. import cv2
  4. import numpy as np
  5. import re
  6. import os
  7. import logging
  8. import io
  9. def create_folder(folder_name):
  10. if not os.path.exists(folder_name):
  11. os.makedirs(folder_name)
  12. def CountPages(file_path):
  13. """
  14. 根据编号创建文件夹
  15. :param file_path:
  16. :return:
  17. """
  18. with pdfplumber.open(file_path) as pdf:
  19. count = 0
  20. for page in pdf.pages:
  21. count += 1
  22. print(f"----------- 第{count}页 ----------- \n\n")
  23. text = page.extract_text()
  24. matches = re.findall(r'编号\s*(\S+)', text)
  25. if matches:
  26. for match in matches:
  27. if '*' in match:
  28. logging.warning(f'编号名称存在不能使用的字符,需要单独调整,Page {count}, 编号后面的内容: {match}')
  29. folder_name = 'new_files/' + f'000 error Page_{count}'
  30. # continue
  31. else:
  32. # folder_name = './new_files/' + match
  33. folder_name = './new_files/' + f'{count}_' + match
  34. create_folder(folder_name)
  35. images = page.images
  36. print(f'images: {images}')
  37. for i, img in enumerate(images):
  38. # x0, y0, x1, y1 = img["x0"], img["y0"], img["x1"], img["y1"]
  39. img_stream = img["stream"]
  40. # 从流中提取图像数据
  41. img_data = img_stream.get_data()
  42. # 使用数据创建新图像
  43. pil_img = Image.open(io.BytesIO(img_data))
  44. # 将图像保存为 JPG
  45. img_filename = f"{folder_name}/image_{count}_{i + 1}.jpg"
  46. pil_img.save(img_filename, format="JPEG")
  47. print(f"保存图像:{img_filename}")
  48. return count
  49. """
  50. 1 需要先将文档转换为 pdf
  51. 2 文件夹名称不要页码改 39 行
  52. 3 编号最好不要出现 * 这种不能作为文件名的符号
  53. 4 filePath 改文件路径
  54. 5 保存文件在同级文件目录下
  55. """
  56. # filePath = r"E:\11-normal_program\registration_card.pdf"
  57. filePath = r"./registration_card.pdf"
  58. CountPages(filePath)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51422
推荐阅读
相关标签
  

闽ICP备14008679号