如何使用pymupdf从较大的pdf中选择的页面中提取文本?

2024-04-26 07:48:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有很多库可以从PDF中提取文本。具体来说,我在使用pymupdf时遇到了一些困难。 从这里的文档:https://pymupdf.readthedocs.io/en/latest/app4.html#sequencetypes 我希望使用select()来选择页面间隔,然后使用getText()这是我正在使用的文档linear_regression.pdf

import fitz
s = [1, 2]
doc = fitz.open('linear_regression.pdf')
selection = doc.select(s)
text = selection.getText(s)

但我得到了这个错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-c05917f260e7> in <module>()
      6 # print(selection)
      7 # text = doc.get_page_text(3, "text")
----> 8 text = selection.getText(s)
      9 text

AttributeError: 'NoneType' object has no attribute 'getText'

所以我假设select()没有被正确使用 非常感谢


Tags: text文档https文本docpdfselectgettext
1条回答
网友
1楼 · 发布于 2024-04-26 07:48:13

select这里,根据the documentation,在内部修改doc,不返回任何内容。在Python中,如果函数没有显式返回任何内容,它将返回None,这就是您看到该错误的原因

但是,Document提供了一个名为get_page_textmethod,允许您从特定页面(0索引)获取文本。因此,对于您的示例,您可以写:

import fitz
s = [1, 2] # pages 2 and 3
doc = fitz.open('linear_regression.pdf')
text_by_page = [doc.get_page_text(i) for i in s]

现在,您有了一个列表,其中列表中的每个项目都是来自不同所需页面的文本。将其转换为字符串的简单方法是:

text = ' '.join(text_by_page)

它在第一页的最后一个字和最后一页的第一个字之间用空格连接两页(好像根本没有分页符)

相关问题 更多 >