使用Python3.4提取PDF文本

时间:2015-06-24 10:11:12

标签: pdf python-3.x pdf-parsing pdfminer

pdf文件中的文本是文本格式,未扫描。 PDFMiner不支持python3,还有其他解决方案吗?

3 个答案:

答案 0 :(得分:3)

还有pdfminer2 fork,支持python 3.4,可通过pip3获得。 https://github.com/metachris/pdfminer

This thread帮我修补了一些东西。

from urllib.request import urlopen
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO, BytesIO

def readPDF(pdfFile):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)

    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()
    for page in PDFPage.get_pages(pdfFile, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    device.close()
    textstr = retstr.getvalue()
    retstr.close()
    return textstr

if __name__ == "__main__":
    #scrape = open("../warandpeace/chapter1.pdf", 'rb') # for local files
    scrape = urlopen("http://pythonscraping.com/pages/warandpeace/chapter1.pdf") # for external files
    pdfFile = BytesIO(scrape.read())
    outputString = readPDF(pdfFile)
    print(outputString)
    pdfFile.close()    

答案 1 :(得分:1)

对于python3,您可以将pdfminer下载为:

python -m pip install pdfminer.six

答案 2 :(得分:0)

tika最适合我。如果我说它比PyPDF2pdfminer更好,那就没错,这使得将pdf中的每一行提取到列表中变得非常容易。您可以通过pip install tika安装它 并且,使用下面的代码:

from tika import parser
rawText = parser.from_file(path_to_pdf)
rawList = rawText['content'].splitlines()
print(rawList)