86 lines
2.4 KiB
Python
86 lines
2.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""提取电机 PDF 数据手册的文字内容,输出到 motor_pdf_dump.txt"""
|
||
import sys, io, os
|
||
|
||
try:
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
|
||
except Exception:
|
||
pass
|
||
|
||
SRC = r"C:\Users\ruigu\Downloads\DS-LE-INTEGRATED-EN(002) (1).pdf"
|
||
OUT = r"d:\开发\OnebotCatalog\motor_pdf_dump.txt"
|
||
|
||
def try_extract():
|
||
joined = ""
|
||
|
||
# 1) pypdf
|
||
try:
|
||
from pypdf import PdfReader
|
||
r = PdfReader(SRC)
|
||
parts = []
|
||
for i, p in enumerate(r.pages):
|
||
parts.append(f"--- PAGE {i+1} ---\n" + (p.extract_text() or ""))
|
||
joined = "\n".join(parts)
|
||
if len(joined.strip()) > 50:
|
||
return "pypdf", len(r.pages), joined
|
||
except Exception as e:
|
||
print("[pypdf fail]", repr(e))
|
||
|
||
# 2) PyPDF2
|
||
try:
|
||
import PyPDF2
|
||
r = PyPDF2.PdfReader(SRC)
|
||
parts = []
|
||
for i, p in enumerate(r.pages):
|
||
parts.append(f"--- PAGE {i+1} ---\n" + (p.extract_text() or ""))
|
||
joined = "\n".join(parts)
|
||
if len(joined.strip()) > 50:
|
||
return "PyPDF2", len(r.pages), joined
|
||
except Exception as e:
|
||
print("[PyPDF2 fail]", repr(e))
|
||
|
||
# 3) pdfplumber
|
||
try:
|
||
import pdfplumber
|
||
parts = []
|
||
with pdfplumber.open(SRC) as pdf:
|
||
for i, p in enumerate(pdf.pages):
|
||
parts.append(f"--- PAGE {i+1} ---\n" + (p.extract_text() or ""))
|
||
joined = "\n".join(parts)
|
||
if len(joined.strip()) > 50:
|
||
return "pdfplumber", len(parts), joined
|
||
except Exception as e:
|
||
print("[pdfplumber fail]", repr(e))
|
||
|
||
# 4) pdfminer.six
|
||
try:
|
||
from pdfminer.high_level import extract_text
|
||
joined = extract_text(SRC)
|
||
if len(joined.strip()) > 50:
|
||
return "pdfminer", "?", joined
|
||
except Exception as e:
|
||
print("[pdfminer fail]", repr(e))
|
||
|
||
return None, 0, ""
|
||
|
||
def main():
|
||
if not os.path.exists(SRC):
|
||
print("MISSING:", SRC)
|
||
return
|
||
|
||
lib, pages, text = try_extract()
|
||
if not lib:
|
||
print("NO_TEXT_EXTRACTED(可能是扫描/图片型 PDF)")
|
||
return
|
||
|
||
with open(OUT, "w", encoding="utf-8") as f:
|
||
f.write(text)
|
||
print("DONE")
|
||
print("库:", lib, "| 页数:", pages, "| 字符数:", len(text))
|
||
print("输出:", OUT)
|
||
print("=" * 60)
|
||
print(text[:4000])
|
||
|
||
if __name__ == "__main__":
|
||
main()
|