我试图使用Python提取包含在这个PDF文件中的文本。

我正在使用PyPDF2包(版本1.27.2),并有以下脚本:

import PyPDF2

with open("sample.pdf", "rb") as pdf_file:
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    number_of_pages = read_pdf.getNumPages()
    page = read_pdf.pages[0]
    page_content = page.extractText()
print(page_content)

当我运行代码时,我得到以下输出,这与PDF文档中包含的输出不同:

 ! " # $ % # $ % &% $ &' ( ) * % + , - % . / 0 1 ' * 2 3% 4
5
 ' % 1 $ # 2 6 % 3/ % 7 / ) ) / 8 % &) / 2 6 % 8 # 3" % 3" * % 31 3/ 9 # &)
%

如何提取PDF文档中的文本?


当前回答

目的:从PDF中提取文本

所需工具:

Poppler for windows: windows中pdftotext文件的包装器 对于anaanaconda: conda install -c conda-forge pdftotext实用程序转换PDF到文本。

步骤: 安装荡漾。windows操作系统:在env路径下增加“xxx/bin/” PIP安装pdftotext

import pdftotext
 
# Load your PDF
with open("Target.pdf", "rb") as f:
    pdf = pdftotext.PDF(f)
 
# Save all text to a txt file.
with open('output.txt', 'w') as f:
    f.write("\n\n".join(pdf))

其他回答

我在这里找到了一个解决方案PDFLayoutTextStripper

这很好,因为它可以保持原始PDF的布局。

它是用Java编写的,但我已经添加了一个网关来支持Python。

示例代码:

from py4j.java_gateway import JavaGateway

gw = JavaGateway()
result = gw.entry_point.strip('samples/bus.pdf')

# result is a dict of {
#   'success': 'true' or 'false',
#   'payload': pdf file content if 'success' is 'true'
#   'error': error message if 'success' is 'false'
# }

print result['payload']

示例输出PDFLayoutTextStripper:

你可以在这里看到更多细节Stripper with Python

Camelot似乎是在Python中从pdf中提取表的一个相当强大的解决方案。

乍一看,它似乎实现了几乎和CreekGeek建议的tabura -py包一样准确的提取,CreekGeek在可靠性方面已经超过了任何其他发布的解决方案,但它应该是更可配置的。此外,它有自己的精度指示器(results.parsing_report),以及强大的调试功能。

Camelot和Tabula都将结果作为Pandas的dataframe提供,因此之后很容易调整表。

pip install camelot-py

(不要与卡梅洛特的包装混淆。)

import camelot

df_list = []
results = camelot.read_pdf("file.pdf", ...)
for table in results:
    print(table.parsing_report)
    df_list.append(results[0].df)

它还可以输出结果为CSV, JSON, HTML或Excel。

卡梅洛特的到来是以牺牲许多属地为代价的。

NB :由于我的输入非常复杂,有许多不同的表,我最终使用Camelot和Tabula,根据表,以达到最好的结果。

下面是提取文本的最简单代码

代码:

# importing required modules
import PyPDF2

# creating a pdf file object
pdfFileObj = open('filename.pdf', 'rb')

# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

# printing number of pages in pdf file
print(pdfReader.numPages)

# creating a page object
pageObj = pdfReader.getPage(5)

# extracting text from page
print(pageObj.extractText())

# closing the pdf file object
pdfFileObj.close()

我尝试过许多Python PDF转换器,我想更新这篇评论。蒂卡是最棒的之一。但是PyMuPDF是@ehsaneha用户的好消息。

我做了一个代码来比较一下:https://github.com/erfelipe/PDFtextExtraction希望对大家有所帮助。

Tika-Python是Apache Tika™REST服务的Python绑定 允许在Python社区中本地调用Tika。

from tika import parser

raw = parser.from_file("///Users/Documents/Textos/Texto1.pdf")
raw = str(raw)

safe_text = raw.encode('utf-8', errors='ignore')

safe_text = str(safe_text).replace("\n", "").replace("\\", "")
print('--- safe text ---' )
print( safe_text )

您可能希望使用经过时间验证的xPDF和派生工具来提取文本,因为pyPDF2在文本提取方面似乎仍然存在各种问题。

长的答案是,文本如何在PDF中编码有很多变化,它可能需要解码PDF字符串本身,然后可能需要与CMAP映射,然后可能需要分析单词和字母之间的距离等。

如果PDF被损坏(即显示正确的文本,但复制时产生垃圾),并且您确实需要提取文本,那么您可能需要考虑将PDF转换为图像(使用ImageMagik),然后使用Tesseract使用OCR从图像中获取文本。