【发布时间】:2019-02-22 05:28:43
【问题描述】:
背景:
我有一个包含多页的 PDF 文件 (LARGE_PDF)。每个页面都包含一个表格,没有其他内容。每张桌子看起来都不一样。我想提取表格内容并将它们放入熊猫数据框中。我为此使用tabula-py,它可以通过以下方法按需要工作:
方法:
首先,我将 PDF 文件拆分为多个单页 PDF 文件并保存到光盘。
single_page_files = split_and_save(LARGE_PDF) # Split to single files, one page each
其次,将每个文件提供给 tabula-py。
from tabula import read_pdf as tabular_read
for item in single_page_files:
print type(item)
df = tabular_read(PDF_page, pandas_options={'header':None})
if df:
print 'approach works'
输出:
>>> <type 'str'> # filepath string
>>> approach works
挑战:
我现在想在内存中执行此操作,以便不会将中间单页 pdf 文件保存到磁盘。为此,我创建了一个单页 PyPDF2.pdf.PageObject 对象列表并将它们提供给 tabula-py。
from PyPDF2 import PdfFileReader, PdfFileWriter
single_page_pypdfobjects = split_but_dont_save(LARGE_PDF)
for item in single_page_pypdfobjects:
print type(item)
df = tabular_read(PDF_page, pandas_options={'header':None})
if df:
print 'approach works'
输出:
>>> class 'PyPDF2.pdf.PageObject'> # PyPDF2 single page object
>>> TypeError: unhashable type
如何使用 python 处理内存中的 PDF?
【问题讨论】:
-
看看here。
标签: python pdf in-memory pypdf2