我试图使用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文档中的文本?


当前回答

我在寻找一个简单的解决方案来使用python 3。X和窗口。textract似乎不支持,这是不幸的,但如果你正在寻找一个简单的解决方案的windows/python 3签出tika包,真的直接阅读pdf。

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

from tika import parser # pip install tika

raw = parser.from_file('sample.pdf')
print(raw['content'])

注意,Tika是用Java编写的,因此需要安装Java运行时

其他回答

你可以从这里下载tika-app-xxx.jar(最新)。

然后将这个.jar文件放在python脚本文件的同一文件夹中。

然后在脚本中插入如下代码:

import os
import os.path

tika_dir=os.path.join(os.path.dirname(__file__),'<tika-app-xxx>.jar')

def extract_pdf(source_pdf:str,target_txt:str):
    os.system('java -jar '+tika_dir+' -t {} > {}'.format(source_pdf,target_txt))

该方法的优点:

更少的依赖。单个.jar文件比python包更容易管理。

开始支持。位置source_pdf可以是任何类型文档的目录。(.doc, .html, .odt等)

最新的。tika-app.jar始终先于相关版本的tika python包发布。

稳定。它比PyPDF更加稳定和维护良好(由Apache提供支持)。

劣势:

一个无头小丑是必要的。

我尝试过许多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 )

如果您在Windows上的Anaconda中尝试它,PyPDF2可能无法处理一些具有非标准结构或unicode字符的pdf。如果您需要打开并阅读大量pdf文件,我建议使用以下代码-相对路径为。//pdfs//的文件夹中所有pdf文件的文本将存储在列表pdf_text_list中。

from tika import parser
import glob

def read_pdf(filename):
    text = parser.from_file(filename)
    return(text)


all_files = glob.glob(".\\pdfs\\*.pdf")
pdf_text_list=[]
for i,file in enumerate(all_files):
    text=read_pdf(file)
    pdf_text_list.append(text['content'])

print(pdf_text_list)

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

代码:

# 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 3中该问题的解决方案。在运行代码之前,请确保已在您的环境中安装了PyPDF2库。如果未安装,打开命令提示符,执行以下命令:

pip3 install PyPDF2

使用PyPDF2 <= 1.26.0的解决方案代码:

import PyPDF2
pdfFileObject = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
count = pdfReader.numPages
for i in range(count):
    page = pdfReader.getPage(i)
    print(page.extractText())