【问题标题】:how to extract text from a selection of pages in a larger pdf using pymupdf?如何使用pymupdf从较大的pdf中的选定页面中提取文本?
【发布时间】:2021-08-19 06:10:14
【问题描述】:

我知道有很多库可以从 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() 没有被正确使用 非常感谢

【问题讨论】:

  • 问题是doc.select(s) 正在返回None。但是,您没有在此处定义 doc,因此不清楚这是为什么。请编辑您的问题以提供minimal, reproducible example
  • 谢谢@Kraigolas,我根据您的反馈编辑了帖子

标签: python pdf nlp pymupdf


【解决方案1】:

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)

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

【讨论】:

  • 这非常有用@Kraigolas 我对如何使用 pyMupdf 有了更好的了解
  • @KatieMelosto 很高兴我能帮上忙!
猜你喜欢
  • 2022-08-05
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 2022-09-26
  • 2012-06-15
  • 2016-01-28
  • 1970-01-01
  • 2011-08-16
相关资源
最近更新 更多