美文网首页
PDF表格信息提取

PDF表格信息提取

作者: StataPython数据分析 | 来源:发表于2020-06-24 13:27 被阅读0次

    本文作者:王碧琪
    文字编辑:钱梦璇
    技术总编:张 邯

    在《提取PDF文本信息:入门》中,我们介绍了使用pdfminer提取PDF中的信息,其中提取的是文本内容,而对于表格内容,使用pdfminer会输出无格式的文本,不能保留表格格式,而pdfplumber就能很好的解决问题。本文将比较两个方法的差异。
    待处理的PDF文档中的表格如下:

    image

    一、pdfminer

    我们用以下程序使用pdfminer进行提取(具体原理已在上篇文章中详述):

    from pdfminer.pdfparser import PDFParser, PDFDocument
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
    from pdfminer.converter import PDFPageAggregator
    from pdfminer.layout import *
    
    parser = PDFParser(open(r"d: \table.pdf"))  
    doc = PDFDocument() 
    parser.set_document(doc) 
    doc.set_parser(parser) 
    
    rsrcmgr = PDFResourceManager() #创建PDF资源管理器来管理共享资源
    laparams = LAParams() #创建一个PDF设备对象
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device) #创建一个PDF解释器对象
    
    with open(r"d:\table.txt", 'w') as f:
        for page in doc.get_pages(): #循环遍历列表,每次处理一个page的内容
            interpreter.process_page(page)
            layout = device.get_result()
            for x in layout:
                if isinstance(x, LTTextBox):
                    print(x.get_text().strip())
                    f.write(x.get_text().strip()+"\n")
    
    

    结果为:

    2010
    Things
    Quantity
    Apples
    Oranges
    Pears
    10
    20
    8
    
    

    由于只能提取文字,这样的结果已经破坏了最初的表格样式。

    二、pdfplumber

    首先导入库,生成pdfplumber对象:

    import pdfplumber 
    pdf = pdfplumber.open(r"d: \table.pdf") 
    print(pdf)
    
    

    结果如下:

    <pdfplumber.pdf.PDF object at 0x000001A536631DC8>
    
    

    结果表明生成了一个pdfplumber对象,我们可以调用.pages()方法解析得到每一页的内容:

    pages=pdf.pages 
    print(pages)
    
    

    结果如下:

    [<pdfplumber.page.Page object at 0x000001A534FD8348>]
    
    

    生成的可迭代对象可以通过for遍历:

    for p in pages:
        table1=p.extract_table()
        print(table1)
    
    

    结果如下:

    [['2010', None], ['Things', 'Quantity'], ['Apples', '10'], ['Oranges', '20'], ['Pears', '8']]
    
    

    table1是一个列表,到这里我们就得到了文档中的表格内容了。列表table1中有若干个小列表,分别表示表格内容中的每一行,每个小列表中有两个元素,虽然原表格内容的第一行只有一个元素,但是这里的结果是补齐成两个元素。我们逐行打印出来。

    for unitrow in table1:
    print(unitrow)
    
    

    结果如下:

    ['2010', None]
    ['Things', 'Quantity']
    ['Apples', '10']
    ['Oranges', '20']
    ['Pears', '8']
    
    

    另外,这里为了更清晰明了地展示列表内容,可以引入pandas库。

    import pandas as pd
    
    df=pd.DataFrame(table1[1:],columns=table1[0])
    print(df)
    
    

    结果如下:


    image

    这样,就得到了比较规整的保留原格式的PDF表格内容了。PDF文档的内容提取比较费工夫,这里提供的表格内容提取方式相对比较成熟。接下来,小编将继续探索PDF文档的内容提取方式,敬请关注~

    相关文章

      网友评论

          本文标题:PDF表格信息提取

          本文链接:https://www.haomeiwen.com/subject/mhsrfktx.html