使用PyMuPDF提取PDF文本为何返回空列表?
PyMuPDF提取PDF文本返回空列表的解决办法
1. 代码本身的问题:缺少输出语句
你的代码逻辑没问题,但最后只是将提取结果赋值给了text变量,没有打印输出,所以看不到任何内容。在if __name__ == '__main__':代码块末尾添加print(text),就能看到返回的列表内容了。
2. PDF本身是图片转的,无原生文本
从文件名png2pdf.pdf来看,这个PDF大概率是由图片转换而来的。这类PDF的内容是图像数据,没有可直接提取的原生文本,所以page.get_text()会返回空字符串,最终得到空列表。
这种情况需要用OCR(光学字符识别)提取图片中的文本,以下是结合PyMuPDF和Tesseract OCR的修改方案:
先安装依赖
pip install pymupdf pytesseract pillow
另外需要单独安装Tesseract OCR引擎:
- Mac:通过Homebrew安装
brew install tesseract - Windows:从官方渠道下载安装包,安装后需将Tesseract的可执行文件路径添加到系统环境变量中
修改后的代码
import fitz import pytesseract from PIL import Image def extract_text_from_pdf(file_path): pdf_document = fitz.open(file_path) text = [] for page in pdf_document: # 先尝试提取原生文本 page_text = page.get_text() if page_text.strip(): text.append(page_text) else: # 提取不到则转成图片做OCR pix = page.get_pixmap() img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) ocr_text = pytesseract.image_to_string(img) text.append(ocr_text) pdf_document.close() return text if __name__ == '__main__': file_path = "/Users/conor/Desktop/projects/png2pdf.pdf" text = extract_text_from_pdf(file_path) print(text) # 打印提取结果
内容的提问来源于stack exchange,提问作者john da bon
相关产品推荐
相关产品推荐

