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


当前回答

你可以使用PDFtoText https://github.com/jalan/pdftotext

PDF到文本保持文本格式缩进,不管你是否有表格。

其他回答

Pdfplumber是一个更好的从pdf中读取和提取数据的库。它还提供了读取表数据的方法,在经历了大量这样的库之后,pdfplumber最适合我。

请注意,它最适合机器编写的pdf,而不是扫描的pdf。

import pdfplumber
with pdfplumber.open(r'D:\examplepdf.pdf') as pdf:
first_page = pdf.pages[0]
print(first_page.extract_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)

试试borb,一个纯python PDF库

import typing  
from borb.pdf.document import Document  
from borb.pdf.pdf import PDF  
from borb.toolkit.text.simple_text_extraction import SimpleTextExtraction  


def main():

    # variable to hold Document instance
    doc: typing.Optional[Document] = None  

    # this implementation of EventListener handles text-rendering instructions
    l: SimpleTextExtraction = SimpleTextExtraction()  

    # open the document, passing along the array of listeners
    with open("input.pdf", "rb") as in_file_handle:  
        doc = PDF.loads(in_file_handle, [l])  
  
    # were we able to read the document?
    assert doc is not None  

    # print the text on page 0
    print(l.get_text(0))  

if __name__ == "__main__":
    main()

在2020年,上述解决方案并不适用于我正在使用的特定pdf。下面是诀窍。我用的是Windows 10和Python 3.8

测试pdf文件:https://drive.google.com/file/d/1aUfQAlvq5hA9kz2c9CyJADiY3KpY3-Vn/view?usp=sharing

#pip install pdfminer.six
import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    '''Convert pdf content from a file path to text

    :path the file path
    '''
    rsrcmgr = PDFResourceManager()
    codec = 'utf-8'
    laparams = LAParams()

    with io.StringIO() as retstr:
        with TextConverter(rsrcmgr, retstr, codec=codec,
                           laparams=laparams) as device:
            with open(path, 'rb') as fp:
                interpreter = PDFPageInterpreter(rsrcmgr, device)
                password = ""
                maxpages = 0
                caching = True
                pagenos = set()

                for page in PDFPage.get_pages(fp,
                                              pagenos,
                                              maxpages=maxpages,
                                              password=password,
                                              caching=caching,
                                              check_extractable=True):
                    interpreter.process_page(page)

                return retstr.getvalue()


if __name__ == "__main__":
    print(convert_pdf_to_txt('C:\\Path\\To\\Test_PDF.pdf')) 

如何从PDF文件中提取文本?

首先要了解的是PDF格式。它有一个用英文编写的公共规范,请参阅ISO 32000-2:2017,并阅读超过700页的PDF 1.7规范。当然,你至少需要阅读维基百科关于PDF的页面

一旦你理解了PDF格式的细节,提取文本或多或少是容易的(但是出现在图形或图像中的文本呢?它的数字1)?不要指望在几周内单独编写一个完美的软件文本提取器....

在Linux上,你也可以使用pdf2text,你可以从你的Python代码中弹出。

一般来说,从PDF文件中提取文本是一个定义不清的问题。对于人类读者来说,一些文本可以由不同的点制成(图形),或者一张照片等等。

谷歌搜索引擎能够从PDF中提取文本,但据传需要超过5亿行的源代码。你有必要的资源(人力和预算)来发展一个竞争对手吗?

一种可能是将PDF打印到一些虚拟打印机(例如使用GhostScript或Firefox),然后使用OCR技术提取文本。

相反,我建议处理生成PDF文件的数据表示,例如原始的LaTeX代码(或Lout代码)或OOXML代码。

在所有情况下,您都需要为至少几个人年的软件开发预算。