diff options
| author | Yasutake Yohei <61961825+yasutakeyohei@users.noreply.github.com> | 2026-11-20 14:23:23 +0900 |
|---|---|---|
| committer | Yasutake Yohei <61961825+yasutakeyohei@users.noreply.github.com> | 2026-11-20 14:23:23 +0900 |
| commit | 8c1874e1fb967b507467f6218935d2f7fe65b5da (patch) | |
| tree | a23b052323d0fd893f4853eaad0377f113036faf /scripts/extract-shihou-text.py | |
| parent | 4f7cb7d1fa13fc356813ed5fbb61bac72f327012 (diff) | |
verify-shihou.mjs: 市報PDFと抽出ドラフトの照合スクリプトを追加
- PDFの文字を内容ストリーム順に取り出し、ドラフトの日付・電話番号・市HP IDを照合する
- 抽出は scripts/extract-shihou-text.py、照合は npm run shihou:verify
- NGは「PDFに無い」と断定せず、目視確認を促す
Diffstat (limited to 'scripts/extract-shihou-text.py')
| -rw-r--r-- | scripts/extract-shihou-text.py | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/scripts/extract-shihou-text.py b/scripts/extract-shihou-text.py new file mode 100644 index 0000000..0ce5fe8 --- /dev/null +++ b/scripts/extract-shihou-text.py @@ -0,0 +1,57 @@ +# 市報こだいらのPDFから、照合に使うテキストを取り出す。 +# +# 使い方: +# py -X utf8 scripts/extract-shihou-text.py ../作業tmp/市報こだいら/20261120号 +# py -X utf8 scripts/extract-shihou-text.py <フォルダ> # フォルダ内の*.pdfをまとめて処理 +# +# PDFの文字は、内容ストリームの順に並べると読み順になる(Adobe等で全選択してコピーしたのと同じ順)。 +# 座標で並べ替えると縦組み・横組みが混ざって崩れるため、ここでは「並べ替えずに」連結する。 +# 出力: 同じフォルダに「○面-pdftext.txt」(例: 6面-pdftext.txt) +import glob +import os +import re +import sys +import unicodedata + +import pdfplumber + + +def label_from_name(name: str) -> str: + """「市報こだいら令和8年11月20日号(6面).pdf」→「6面」""" + base = os.path.basename(name).replace(".pdf", "") + m = re.search(r"[((]([^))]+)[))]\s*$", base) + return m.group(1).strip() if m else base + + +def extract(path: str) -> str: + with pdfplumber.open(path) as pdf: + raw = "".join( + c["text"] for page in pdf.pages for c in page.chars if c.get("text") + ) + return unicodedata.normalize("NFKC", raw) + + +def main() -> int: + if len(sys.argv) < 2: + print(__doc__ or "使い方: extract-shihou-text.py <フォルダ>", file=sys.stderr) + return 2 + + folder = os.path.abspath(sys.argv[1]) + pdfs = sorted(glob.glob(os.path.join(folder, "*.pdf"))) + if not pdfs: + print(f"PDFがありません: {folder}", file=sys.stderr) + return 1 + + for path in pdfs: + label = label_from_name(path) + text = extract(path) + out = os.path.join(folder, f"{label}-pdftext.txt") + with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write(text + "\n") + print(f"{label}: {len(text)}文字 -> {os.path.basename(out)}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) |
