1

我有一些 PDF 文档无法使用 PyPDF 提取文本,只能使用 PDFMiner。以下代码可以很好地从 PDF 中提取所有文本,它遍历整个文档,然后返回所有文本。有没有办法只处理 PDF 的某些页面?我拥有的 PDF 都是 2000-3000 长,我只需要处理每一页。

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

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec,laparams=laparams)
    fp = file(path, 'rb')
    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)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text
4

1 回答 1

2

您不能enumerate在遍历所有页面时使用获取页码和页面内容吗?如果您只想要每隔一页,请使用模数。如果您只想要特定页面,请使用范围。

例子:

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

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec,laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for pagenumber, page in enumerate(PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True)):
        print pagenumber
        if pagenumber % 2 == 0:
            print("even page number")
            interpreter.process_page(page)
        else:
            print("odd page number")
        if 5 <= pagenumber <= 10:
            print("pages 5 to 10")

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text
于 2016-03-08T14:37:50.663 回答