当前位置: 首页 > news >正文

python将pdf转txt,并切割ai

python将pdf转txt,并切割ai

step1:pdf转换

from PIL import Image
import pytesseract
import os
import tempfile
from pdf2image import convert_from_path# 设置 Tesseract 路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\wangrusheng\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'# 设置 Poppler 路径
POPPLER_PATH = r'C:\Users\wangrusheng\AppData\Local\Programs\poppler-24.08.0\Library\bin'def pdf_to_txt(input_pdf, output_txt):"""将PDF文件转换为文本文件参数:input_pdf -- 输入的PDF文件路径output_txt -- 输出的文本文件路径"""# 创建临时目录存储转换后的图片with tempfile.TemporaryDirectory() as temp_dir:# 将PDF转换为图片列表images = convert_from_path(input_pdf,poppler_path=POPPLER_PATH,  # 添加关键配置output_folder=temp_dir,dpi=300,fmt='jpeg',thread_count=4)# 打开输出文件with open(output_txt, 'w', encoding='utf-8') as f:# 处理每一页图片for i, image in enumerate(images):try:# 使用OCR识别文字text = pytesseract.image_to_string(image,lang='chi_sim+eng+jpn+rus+tha+kor+ara'  # 中英文混合识别)# 写入识别结果f.write(f"--- 第 {i + 1} 页内容 ---\n")f.write(text.strip())f.write("\n\n")print(f"已处理第 {i + 1} 页")except Exception as e:error_msg = f"第 {i + 1} 页识别失败: {str(e)}"print(error_msg)f.write(error_msg + "\n")print(f"\n转换完成!结果已保存至: {output_txt}")if __name__ == "__main__":# 输入PDF路径input_pdf = r"C:\Users\wangrusheng\Downloads\sdf.pdf"# 输出TXT路径output_txt = os.path.join(os.path.dirname(input_pdf),os.path.splitext(os.path.basename(input_pdf))[0] + ".txt")# 执行转换pdf_to_txt(input_pdf, output_txt)

step2:

import osdef read_txt_file(txt_path):"""读取TXT文件内容"""with open(txt_path, 'r', encoding='utf-8') as f:return f.read()def split_text_by_size(text, max_bytes, output_dir):"""按文件大小切割文本(确保不截断行和UTF-8字符):param text: 完整文本内容:param max_bytes: 每个文件的最大字节数:param output_dir: 输出文件目录:return: 生成的文件列表"""# 确保输出目录存在os.makedirs(output_dir, exist_ok=True)# 计算备注信息的字节大小(UTF-8编码)note_text = """请ai保持批判性思维,模仿袁的口吻,讲述材料中的历史故事。具体要求如下:1.
风格: 采用经典的评书口吻和结构。例如,开头要有上一回和下一回的标题,内容部分必须拆分小标题,小段落,能拆分的全部拆分2.
内容:•
严格遵循历史: 只讲述真实发生的事件、人物和时间,不能有任何虚构或戏说。•
逻辑连贯: 清晰解释事件发生的原因、过程和结果。•
自动补全背景: 在故事中自然地融入必要的背景信息,让逻辑连贯,转场丝滑。3.
语言: 绝对简单易懂,使用口语化的词汇和短句,让小学生能毫无障碍地听懂故事里发生了什么事。可以用夸张,比喻,隐喻,讽刺等手法,但需基于史实。请从‘第一回:xxx’开始讲起。
"""  # 修改后的固定备注信息note_bytes = note_text.encode('utf-8')note_size = len(note_bytes)# 调整最大字节数(预留备注信息空间)max_bytes = max_bytes - note_sizeif max_bytes <= 0:raise ValueError("文件大小设置过小,无法容纳备注信息")# 初始化字母组合生成器def generate_suffix():for first in range(26):for second in range(26):yield f"{chr(97 + first)}{chr(97 + second)}"suffix_gen = generate_suffix()files_created = []encoded_text = text.encode('utf-8')  # 整个文本的UTF-8字节表示while encoded_text:# 获取当前块的最大字节数chunk_size = min(max_bytes, len(encoded_text))# 查找安全切割点(优先在换行符处切割)cut_index = chunk_sizeif b'\n' in encoded_text[:chunk_size]:# 查找最后一个换行符作为切割点cut_index = encoded_text.rindex(b'\n', 0, chunk_size) + 1else:# 尝试在字符边界处切割while cut_index > 0:try:# 验证是否在完整字符处encoded_text[:cut_index].decode('utf-8')breakexcept UnicodeDecodeError:cut_index -= 1# 提取当前块并更新剩余文本chunk = encoded_text[:cut_index]encoded_text = encoded_text[cut_index:]# 获取下一个字母组合后缀suffix = next(suffix_gen)# 写入文件(添加备注信息)output_file = os.path.join(output_dir, f"{suffix}.txt")with open(output_file, 'wb') as f:f.write(chunk)f.write(note_bytes)  # 在文件底部添加备注信息files_created.append(output_file)print(f"已创建: {output_file} (大小: {len(chunk) + note_size:,} 字节)")return files_createddef process_txt(input_txt, output_dir, max_size_kb=20):"""处理TXT文件:按大小切割:param input_txt: 输入的TXT文件路径:param output_dir: 输出文件目录:param max_size_kb: 每个文件的最大大小(KB)"""# 检查文件是否存在if not os.path.exists(input_txt):raise FileNotFoundError(f"文件不存在: {input_txt}")# 读取TXT文件text_content = read_txt_file(input_txt)if not text_content.strip():print("警告: 文件内容为空")# 按大小切割max_bytes = max_size_kb * 1024  # KB转为字节return split_text_by_size(text_content, max_bytes, output_dir)# 使用示例
if __name__ == "__main__":input_file = r"C:\Users\wangrusheng\Downloads\ust.txt"  # TXT文件路径output_dir = r"C:\Users\wangrusheng\Downloads\accc"  # 输出文件目录max_size_kb = 15  # 每个文件最大20KBcreated_files = process_txt(input_file, output_dir, max_size_kb)print(f"切割完成! 共生成 {len(created_files)} 个文件")

step3:查询页数

from pdf2image import convert_from_path
import os# 设置 Poppler 路径
POPPLER_PATH = r'C:\Users\wangrusheng\AppData\Local\Programs\poppler-24.08.0\Library\bin'def get_pdf_page_count(input_pdf):"""获取PDF文件的页数参数:input_pdf -- 输入的PDF文件路径返回:page_count -- PDF文件的页数"""# 将PDF转换为图片列表(不写入磁盘)images = convert_from_path(input_pdf,poppler_path=POPPLER_PATH,dpi=50,  # 降低DPI以提高速度fmt='jpeg',thread_count=4,use_pdftocairo=True,  # 使用更稳定的转换引擎strict=False  # 忽略部分错误)return len(images)if __name__ == "__main__":# 输入PDF路径input_pdf = r"D:\Users\wangrusheng\Downloads\pe.pdf"try:page_count = get_pdf_page_count(input_pdf)print(f"PDF文件页数: {page_count}")except Exception as e:print(f"处理PDF时出错: {str(e)}")

end


文章转载自:

http://tLNfbfLG.qptbn.cn
http://cqlHEwZT.qptbn.cn
http://yuvaDIrf.qptbn.cn
http://hN2jjsS7.qptbn.cn
http://8tNzSLjU.qptbn.cn
http://QNJZyZXF.qptbn.cn
http://MnM47TJV.qptbn.cn
http://NxvnVDtj.qptbn.cn
http://aWM6BvT6.qptbn.cn
http://aF6R4BSJ.qptbn.cn
http://TRDWragc.qptbn.cn
http://wyEbc7YZ.qptbn.cn
http://8h6g0919.qptbn.cn
http://1HCIkXvW.qptbn.cn
http://yIjtiOlx.qptbn.cn
http://KnhEc10l.qptbn.cn
http://MxQTLI1m.qptbn.cn
http://q8dvkMh7.qptbn.cn
http://cawVCnIC.qptbn.cn
http://WDfst01A.qptbn.cn
http://IcCF91hD.qptbn.cn
http://18mg4Y9m.qptbn.cn
http://2dDMRA9e.qptbn.cn
http://9CVMQfLu.qptbn.cn
http://kGwJRGq0.qptbn.cn
http://YKtjjomX.qptbn.cn
http://A7stZNo3.qptbn.cn
http://oJzmF1U5.qptbn.cn
http://ZTbi8B6K.qptbn.cn
http://E7NU5FmJ.qptbn.cn
http://www.dtcms.com/a/377967.html

相关文章:

  • 可视化图解算法60: 矩阵最长递增路径
  • 4、幽络源微服务项目实战:后端公共模块创建与引入多租户模块
  • 用Next.js 构建一个简单的 CRUD 应用:集成 API 路由和数据获取
  • 如何通过url打开本地文件文件夹
  • Swagger隐藏入参中属性字段
  • JavaEE--8.网络编程
  • linux系统搭建nacos集群,并通过nginx实现负载均衡
  • 论文阅读:openai 2025 Why Language Models Hallucinate
  • Rail开发日志_9
  • opencv特征检测
  • 科普:环境隔离的工具:虚拟环境与容器Docker
  • 小迪安全v2023学习笔记(八十一讲)—— 框架安全ThinkPHPLaravelStruts2SpringBootCVE复现
  • ubuntu22.04 安装Docker
  • OpenCV 开发 -- 图像阈值处理
  • [Ubuntu][mount]ubuntu电脑挂载新硬盘
  • Maven中optional的作用
  • 使用pdfjs-dist 预览pdf,并添加文本层的实现
  • 操作系统应用开发(五)智能浏览器开发——东方仙盟元婴期
  • 蓝桥杯算法之基础知识(7)---排序题的快排和归并排序
  • leetcode-python-2154将找到的值乘以 2
  • Nginx 实战系列(十)—— LVS+Keepalived 高可用集群技术详解
  • C++ 前缀积 高频笔试考点 实用技巧 力扣 238.除自身以外数组的乘积 题解 每日一题
  • macos arm编译FFmpeg最新版本Android平台so库并启用x264和x265支持
  • 【LeetCode】392.判断子序列
  • StreamCap(直播录制) v1.0.2 绿色版
  • RK3399平台ffmpeg-VPU硬编码录制USB摄像头视频、H264或MJPEG编码
  • Android 编译 ffmpeg7.1.1
  • 什么是 源网荷储一体化和多能互补(光储充微电网解决方案)
  • SpringBoot集成ElasticSearch
  • STL库——AVL树