编程语言
首页 > 编程语言> > python – 使用pdfminer从pdf中提取文本可以提供多个副本

python – 使用pdfminer从pdf中提取文本可以提供多个副本

作者:互联网

我试图使用PDFMiner(在Extracting text from a PDF file using PDFMiner in python?找到的代码)从PDF文件中提取文本.除了path / to / pdf之外,我没有更改代码.令人惊讶的是,代码返回同一文档的多个副本.我得到了与其他pdf文件相同的结果.我是否需要传递其他论点或者我错过了什么?任何帮助都非常感谢.为了以防万一,我提供了代码:

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()
    fstr = ''
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,    password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

        str = retstr.getvalue()
        fstr += str

    fp.close()
    device.close()
    retstr.close()
    return fstr

print convert_pdf_to_txt("test.pdf")

解决方法:

我的答案在您引用的主题中有点不正确.我发现了这个错误并忘了更新我的回答.

因为pdfminer的文档很少,所以我无法完全解释为什么它的工作方式如此.希望能够更好地了解pdfminer库的人可以给我们一些见解.

我所知道的是你必须在for循环之外做text = retstr.getvalue().我只能假设retstr正在更新,好像我们在for循环中执行final_text = text一样,所以一旦完成,我们只需要执行text = retstr.getvalue()来获取所有页面中的文本.

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

print convert_pdf_to_txt("test.pdf")

希望这有帮助!

标签:python,pdf,pdfminer
来源: https://codeday.me/bug/20191009/1875744.html