我希望从PDF导出文本作为字符串列表,其中列表是整个文档,字符串是pdf页面。我正在使用PDFMiner来完成这项任务,但它非常复杂,而且我的截止日期很紧。
到目前为止,我已经得到了将完整pdf提取为字符串的代码,但我需要它以字符串列表的形式出现。
我的代码如下
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from cStringIO import StringIO
f = file('./PDF/' + file_name, 'rb')
data = []
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.get_pages(pdf):
interpreter.process_page(page)
data = retstr.getvalue()
print data请帮帮忙。
发布于 2015-01-31 01:15:12
当前脚本的问题是StringIO.getvalue总是返回一个字符串,该字符串包含到目前为止读取的所有数据。此外,对于每一页,您都要覆盖存储它的变量data。
一个解决方法是在StringIO写入之前存储它的位置,然后从这个位置读取到字符串流的末尾:
# A list for all each page's text
pages_text = []
for page in PDFPage.get_pages(pdf):
# Get (and store) the "cursor" position of stream before reading from PDF
# On the first page, this will be zero
read_position = retstr.tell()
# Read PDF page, write text into stream
interpreter.process_page(page)
# Move the "cursor" to the position stored
retstr.seek(read_position, 0)
# Read the text (from the "cursor" to the end)
page_text = retstr.read()
# Add this page's text to a convenient list
pages_text.append(page_text)将StringIO视为文本文档。您需要在添加文本时管理光标位置,并一次存储新添加的文本一页。在这里,我们将文本存储在一个列表中。
https://stackoverflow.com/questions/28246161
复制相似问题