python将pdf转txt,并切割ai
step1:pdf转换
python
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:
python
import os
def 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_size
if 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_size
if b'\n' in encoded_text[:chunk_size]:
# 查找最后一个换行符作为切割点
cut_index = encoded_text.rindex(b'\n', 0, chunk_size) + 1
else:
# 尝试在字符边界处切割
while cut_index > 0:
try:
# 验证是否在完整字符处
encoded_text[:cut_index].decode('utf-8')
break
except 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_created
def 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 # 每个文件最大20KB
created_files = process_txt(input_file, output_dir, max_size_kb)
print(f"切割完成! 共生成 {len(created_files)} 个文件")
step3:查询页数
python
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