You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3 PDF转TXT代码报错修复及替代实现方案咨询

PDF转TXT代码报错修复及替代方案

报错原因

你遇到的IndexError: list index out of range是页面索引越界导致的:

  • pdfreader.numPages返回PDF总页数,而PyPDF2的页面索引从0开始。比如PDF有5页,合法索引是0-4,你用x + 1(总页数+1)去获取页面,必然超出列表范围。
  • 代码还有其他隐性问题:
    1. pdfFileObj是文件对象,不是文件名,re.sub('pdf$','txt',pdfFileObj)会直接报错,re.sub无法处理文件对象
    2. Windows路径里的反斜杠\会被当作转义字符,需用原始字符串或双反斜杠规避
    3. 只提取了单页内容,未遍历所有页面

修复后的PyPDF2代码

import re
import PyPDF2

# 原始PDF路径
pdf_path = '123.pdf'
# 输出TXT路径,处理文件名和转义路径
txt_path = rf"C:\Users\honorr\Desktop\ssssssss\{re.sub(r'\.pdf$', '.txt', pdf_path)}"

with open(pdf_path, 'rb') as pdfFileObj:
    pdfreader = PyPDF2.PdfReader(pdfFileObj)  # PyPDF2 v2.x版本用PdfReader,替代旧版PdfFileReader
    total_pages = len(pdfreader.pages)  # 新版用len(pdfreader.pages)替代numPages
    
    # 遍历所有页面提取文本
    full_text = ""
    for page_num in range(total_pages):
        pageObj = pdfreader.pages[page_num]
        full_text += pageObj.extract_text() + "\n\n"

# 写入TXT文件
with open(txt_path, 'w', encoding='utf-8') as file1:
    file1.write(full_text)

注:如果使用PyPDF2 v1.x旧版本,可将PdfReader换回PdfFileReader,len(pdfreader.pages)换回pdfreader.numPages。

其他PDF转TXT的实现方法

方法1:使用pdfplumber(提取精度更高)

pdfplumber对文本提取的准确性和布局保留更好,适合复杂格式的PDF:

import pdfplumber
import re

pdf_path = '123.pdf'
txt_path = rf"C:\Users\honorr\Desktop\ssssssss\{re.sub(r'\.pdf$', '.txt', pdf_path)}"

full_text = ""
with pdfplumber.open(pdf_path) as pdf:
    for page in pdf.pages:
        full_text += page.extract_text() + "\n\n"

with open(txt_path, 'w', encoding='utf-8') as f:
    f.write(full_text)

安装命令:pip install pdfplumber

方法2:使用textract(支持多格式)

textract可处理PDF、Word等多种格式,需依赖系统工具(如Poppler):

import textract
import re

pdf_path = '123.pdf'
txt_path = rf"C:\Users\honorr\Desktop\ssssssss\{re.sub(r'\.pdf$', '.txt', pdf_path)}"

# 提取文本
text = textract.process(pdf_path, encoding='utf-8')

# 写入文件
with open(txt_path, 'wb') as f:
    f.write(text)

安装命令:pip install textract
Windows用户需额外安装Poppler并添加到系统环境变量。

内容的提问来源于stack exchange,提问作者Vikvad Newfag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:10:26