Files
OnebotCatalog/tools/extract-pdf.py

35 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
# 提取 PDF 文本到 UTF-8 文件 (PyMuPDF), 并解码内嵌字体私有区数字
# 用法: python extract-pdf.py <pdf> <outdir> <起始页> <结束页(含)>
import fitz, sys, os
path, outdir = sys.argv[1], sys.argv[2]
start = int(sys.argv[3]); end = int(sys.argv[4])
doc = fitz.open(path)
os.makedirs(outdir, exist_ok=True)
# ONEBOT 手册: 数字被编码为私有区字符 0xF6B1(=0) ~ 0xF6BA(=9)
DIGITS = {0xF6B1 + i: str(i) for i in range(10)}
# 常见符号误提取 (按上下文谨慎映射)
SYMBOLS = {'÷': 'x', '': 'x', '·': '-'}
def decode(t):
out = []
for ch in t:
o = ord(ch)
if o in DIGITS:
out.append(DIGITS[o])
elif ch in SYMBOLS:
out.append(SYMBOLS[ch])
else:
out.append(ch)
return ''.join(out)
for i in range(start - 1, min(end, len(doc))):
text = decode(doc[i].get_text())
fn = os.path.join(outdir, "page_%03d.txt" % (i + 1))
with open(fn, "w", encoding="utf-8") as f:
f.write(text)
print("total_pages", len(doc))
print("extracted", start, "to", min(end, len(doc)), "->", outdir)