本文介绍如何使用 Python 解析 PDF 和 Word 文档,提取其中的文本内容,并提供一个统一的解析入口。
1. 安装依赖
1.1 安装 PyMuPDF(PDF 解析)
bash
pip install PyMuPDF
1.2 安装 python-docx(Word 解析)
bash
pip install python-docx
2. PDF 文档解析
2.1 PDF 解析工具类
python
import fitz
class PdfUtil:
@staticmethod
def read(file) -> str:
"""
读取 PDF 文本
"""
text_list = []
pdf = fitz.open(
stream=file.read(),
filetype="pdf"
)
for page in pdf:
text_list.append(
page.get_text()
)
file.seek(0)
return "\n".join(text_list)
2.2 使用示例
python
text = PdfUtil.read(upload_file.file)
print(text)
3. Word 文档解析
3.1 Word 解析工具类
python
from docx import Document
from io import BytesIO
class WordUtil:
@staticmethod
def read(file) -> str:
"""
读取 Word 文本
"""
document = Document(
BytesIO(file.read())
)
text_list = []
for paragraph in document.paragraphs:
if paragraph.text.strip():
text_list.append(
paragraph.text.strip()
)
file.seek(0)
return "\n".join(text_list)
3.2 使用示例
python
text = WordUtil.read(upload_file.file)
print(text)
4. 统一解析入口(推荐)
4.1 统一解析工具类
python
from app.utils.pdf_util import PdfUtil
from app.utils.word_util import WordUtil
class DocumentParser:
@staticmethod
def parse(file_type: str, file) -> str:
"""
统一文档解析
"""
if file_type == "pdf":
return PdfUtil.read(file)
if file_type == "docx":
return WordUtil.read(file)
if file_type == "doc":
return WordUtil.read(file)
raise Exception("不支持的文件类型")
4.2 使用示例
python
# 解析文本
text = DocumentParser.parse(
result.file_type,
self.file.file
)