繁体   English   中英

从 PDF 提取数据到文本文件

[英]Data Extraction from PDF to Text File

我在一个文件夹中有多个 pdf。 我合并所有 pdf 并运行此代码:

    doc = fitz.open(merged.pdf)
    out = open('raw.txt', "wb")
    for page in doc:
        text = page.get_text().encode("utf8")  
        out.write(text)
        out.write(bytes((12,))) 
    out.close()

为了跳过 Pdfs 的合并,到达了这个代码:

from glob import glob
import os

x = "/path"

for pdf in glob(x + os.sep + '*.pdf'):
    
    doc = fitz.open(pdf)  # open document
    out = open('raw.txt', "wb")
    for page in doc:
        text = page.get_text().encode("utf8")  
        out.write(text)
        out.write(bytes((12,))) 
    out.close()

但是,只捕获了一个PDF。 我想在提到的第一个代码上使用相同的 output。

要写入打开的文件,请使用out.write()

with open('.txt','wb') as out:
    out.write(data)

当您保存到文本文件时,您不需要以二进制模式“wb”或“rb”打开它。 但我想这没有什么害处,因为你很可能只会在 pdf 上使用 open() 时出现乱码(?)

安装 PyPDF2 在终端上运行以下命令来安装 PyPDF2。

pip install PyPDF2

导入 PyPDF2 现在您必须导入 PyPDF2 模块。 所以写下面的代码。

import PyPDF2

创建 PDF 文件 Object 编写以下代码创建 PDF 文件 ZA8CFDE6331BD146EB2AC96B861

pdfFileObject = open(r"F:\pdf.pdf", 'rb')

现在你必须打开你的文件来阅读。 open() 方法用于读取 python 中的文件。 并输入您的文件名和文件路径。 该文件以 rb 模式打开(r 用于读取,b 用于二进制)。 PDF 文件被视为二进制文件,因此您需要从二进制文件中读取它。

Creating A PDF Reader Object Now create an object of PdfFileReader class of PyPDF2 module and pass PDF file object that holds the file.

pdfReader = PyPDF2.PdfFileReader(pdfFileObject)

打印 PDF 文件中的页数 您还可以请求文件的页数。 所以只需使用 pdfReader.numPages,它将返回 PDF 文件中的总页数。

print(" No. Of Pages :", pdfReader.numPages)

创建页面 Object 现在您将从特定页面读取特定内容。 So create an object and invoke pdfReader class and getPage() function and inside getPage() function you need to give the page number. 页码应从 0 开始,即 PDF 文件的第一个页码。

pageObject = pdfReader.getPage(0)

从页面中提取文本 extractText() function 用于提取 PDF 的文本。 在此示例中,它将从 PDF 中提取第一页的文本。

print(pageObject.extractText())

关闭 PDF 文件 Object 现在关闭文件 object 编写以下代码。

pdfFileObject.close()

PDF To Text Python Using PyPDF2 Complete Code So here is the complete code of extracting text from PDF file using PyPDF2 module in python.

import PyPDF2
 
pdfFileObject = open(r"F:\pdf.pdf", 'rb')
 
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
 
print(" No. Of Pages :", pdfReader.numPages)
 
pageObject = pdfReader.getPage(0)
 
print(pageObject.extractText())
 
pdfFileObject.close()

现在让我们检查一下它的 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM