【问题标题】:How to extract text from a two-column PDF using PDFPlumber如何使用 PDFPlumber 从两列 PDF 中提取文本
【发布时间】:2021-08-25 08:04:39
【问题描述】:

我正在使用 python 进行主题建模任务,我想从年度/可持续发展报告中提取文本。但是我的问题是,当我尝试提取报告时,提取的行在页面中的两个不同列之间断开,即,它将相邻段落中的两个不同行连接成一个句子。如何完全按照报告中的方式提取线条。我附上了报告的版本和函数提取的行。

下面是我使用的函数:

#函数从url获取pdf

def converter(url):
    text=[]
    req= requests.get(url)
    with pdfplumber.open(BytesIO(req.content)) as pdf:
        for i in range(0, len(pdf.pages)):
            pages= pdf.pages[i]
            text.append(pages.extract_text())
    return "\n".join(str(i) for i in text)

The image is a snippet from the report I am extracting, the text in the report is divided into two columns and the extract_content function mixes up these two columns to get a line, i.e., joins lines in two columns and presents as a single line.

这里是报告的第一行(第一列和第二列的开始,由函数合并在一起):

\n我在 2019 年的首要职责之一是面试我们 踏上了新的战略时期\非“早安挪威”节目 在 2016 年的谈话中,我表示希望 AF 能感受到\n关于 AF 的 当我们的目标是紧密结合的百分比增加一倍 希望超越\n女性

如果我能以报告中给出的确切方式提取句子,将会很有帮助。

【问题讨论】:

    标签: python text-extraction topic-modeling information-extraction pdfplumber


    【解决方案1】:

    这是基于response by samkit-jain 对包上的一个问题。

    密钥是page.crop

    假设没有页眉信息,将页面裁剪成两半:

    left = page.crop((0, 0, 0.5 * page.width, 0.9 * page.height))
    right = page.crop((0.5 * page.width, 0, page.width, page.height)
    

    然后提取文本并连接:

    l_text = left.extract_text()
    r_text = right.extract_text()
    text = l_text + " " + r_text
    

    当然,如果您的报告中的某个页面有一个跨越两列的图形,那么这种方法会搞砸,因此您可能必须在每个页面上自定义它。

    【讨论】:

    • 非常感谢
    • 我如何有条件地做到这一点?仅当页面确实有列文本@Kaia
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多