我想使用python3的pdfminer.six提取pdf。问题在于根本没有好的文档,也没有关于如何使用它的源代码示例。
我已经尝试过StackOverflow的一些代码,但是没有用。我的代码如下。
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io 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 = open(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
我想要一些代码示例,说明如何使用它从pdf获取数据。
答案 0 :(得分:1)
安装pdfminer.six或pdfminer3(https://github.com/gwk/pdfminer3/) 安装:pip install pdfminer3 我从3.6升级到3.7时切换到pdfminer3 我在python 3.7.3上的ubuntu和macos上使用
pdfminer3带有两个方便的工具:pdf2txt.py和dumppdf.py 检查源。很小,很容易理解。
以下是一个可行的示例(一旦添加了pdf文件的位置)
from pdfminer3.layout import LAParams, LTTextBox
from pdfminer3.pdfpage import PDFPage
from pdfminer3.pdfinterp import PDFResourceManager
from pdfminer3.pdfinterp import PDFPageInterpreter
from pdfminer3.converter import PDFPageAggregator
resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(resource_manager, fake_file_handle)
page_interpreter = PDFPageInterpreter(resource_manager, converter)
with open('/path/to/file.pdf', 'rb') as fh:
for page in PDFPage.get_pages(fh,
caching=True,
check_extractable=True):
page_interpreter.process_page(page)
text = fake_file_handle.getvalue()
# close open handles
converter.close()
fake_file_handle.close()
print(text)