使用 PyMUPDF 使用标志提取文本以重点关注粗体/斜体字体

Cam*_*Cam 5 python search bold python-3.x pymupdf

我正在尝试使用 PyMUPDF 1.18.14 从 PDF 中提取粗体文本元素。我希望这能按照我从针对flags=4粗体字体的文档中了解到的那样起作用。

\n
page = doc[1]\ntext = page.get_text(flags=4)\nprint(text)\n
Run Code Online (Sandbox Code Playgroud)\n

但它会打印页面上的所有文本,而不仅仅是粗体文本。

\n

TextPage.extractDICT() (or Page.get_text(\xe2\x80\x9cdict\xe2\x80\x9d))当这样使用时:-

\n
page.get_text("dict", flags=11)["blocks"]\n
Run Code Online (Sandbox Code Playgroud)\n

该标志有效,但我无法理解它在做什么。也许在图像和文本块之间切换。

\n

跨度

\n

所以看来你必须到达span才能访问标志。

\n
<page>\n    <text block>\n        <line>\n            <span>\n                <char>\n    <image block>\n        <img>\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n

所以你可以做这样的事情,我flags=20在 span 标签上使用了粗体字体。

\n
page = doc[1]\nblocks = page.get_text("dict", flags=11)["blocks"]\nfor b in blocks:  # iterate through the text blocks\n    for l in b["lines"]:  # iterate through the text lines\n        for s in l["spans"]:  # iterate through the text spans\n            if s["flags"] == 20:  # 20 targets bold\n                print(s)\n
Run Code Online (Sandbox Code Playgroud)\n

但这似乎还很遥远。

\n

所以我的问题是这是寻找大胆元素的最佳方式还是我遗漏了什么?

\n

能够使用搜索粗体元素会很棒page.search_for()

\n