| 123456789101112131415161718192021 |
- from pathlib import Path
- from docx import Document
- from pypdf import PdfReader
- class DocumentParser:
- @staticmethod
- def parse_file(file_path: str) -> str:
- path = Path(file_path)
- suffix = path.suffix.lower()
- if suffix == ".txt":
- return path.read_text(encoding="utf-8", errors="ignore")
- if suffix == ".docx":
- doc = Document(file_path)
- return "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
- if suffix == ".pdf":
- reader = PdfReader(file_path)
- pages = [page.extract_text() or "" for page in reader.pages]
- return "\n".join(pages)
- return path.read_text(encoding="utf-8", errors="ignore")
|