반응형
PDFMiner를 사용하여 PDF 파일에서 모든 텍스트 상자와 텍스트 상자 좌표를 추출하고 싶습니다.
다른 많은 스택 오버플로 게시물은 순서대로 모든 텍스트를 추출하는 방법을 다루고 있지만 텍스트 및 텍스트 위치를 가져 오는 중간 단계를 어떻게 수행 할 수 있습니까?
PDF 파일이 주어지면 출력은 다음과 같아야합니다.
489, 41, "Signature"
500, 52, "b"
630, 202, "a_g_i_r"
해결 방법
개행은 최종 출력에서 밑줄로 변환됩니다. 이것은 내가 찾은 최소한의 작업 솔루션입니다.
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
import pdfminer
# Open a PDF file.
fp = open('/Users/me/Downloads/test.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Password for initialization as 2nd parameter
document = PDFDocument(parser)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# BEGIN LAYOUT ANALYSIS
# Set parameters for analysis.
laparams = LAParams()
# Create a PDF page aggregator object.
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
def parse_obj(lt_objs):
# loop over the object list
for obj in lt_objs:
# if it's a textbox, print text and location
if isinstance(obj, pdfminer.layout.LTTextBoxHorizontal):
print "%6d, %6d, %s" % (obj.bbox[0], obj.bbox[1], obj.get_text().replace('\n', '_'))
# if it's a container, recurse
elif isinstance(obj, pdfminer.layout.LTFigure):
parse_obj(obj._objs)
# loop over all pages in the document
for page in PDFPage.create_pages(document):
# read the page into a layout object
interpreter.process_page(page)
layout = device.get_result()
# extract text from this object
parse_obj(layout._objs)
참조 페이지 https://stackoverflow.com/questions/22898145
반응형
'파이썬' 카테고리의 다른 글
파이썬 SQLite 매개 변수 대체 문제 (0) | 2020.12.16 |
---|---|
파이썬 함수는 어떻게 객체를 반환합니까? (0) | 2020.12.16 |
파이썬 빈 배열에 대한 ValueError 극복 (0) | 2020.12.16 |
파이썬 Xlsxwriter 파일을 특정 경로에 저장하는 방법은 무엇입니까? (0) | 2020.12.16 |
파이썬 Django 문자열을 날짜 형식으로 (0) | 2020.12.16 |
댓글