2010-06-30 52 views
7

Tôi có một loạt tệp PDF mà tôi cần chuyển đổi sang TXT. Thật không may, khi tôi sử dụng một trong nhiều tiện ích có sẵn để làm điều này, nó mất tất cả các định dạng và tất cả các dữ liệu được lập bảng trong PDF bị lộn xộn. Có thể sử dụng Python để trích xuất văn bản từ PDF bằng cách chỉ định các tư thế, v.v.Trích xuất văn bản từ PDF

Cảm ơn.

+0

Bạn đã tìm kiếm một thư viện có thể trợ giúp điều này? –

+0

Tôi đã không tìm thấy bất kỳ để đọc chúng, nhưng một bó của họ để viết chúng. –

Trả lời

3

Các tệp PDF không chứa dữ liệu dạng bảng trừ khi nó chứa nội dung có cấu trúc. Một số công cụ bao gồm chẩn đoán để thử và đoán cấu trúc dữ liệu và đưa nó trở lại. Tôi đã viết một bài viết blog giải thích các vấn đề với khai thác văn bản PDF tại http://www.jpedal.org/PDFblog/2009/04/pdf-text/

+0

Nếu có cách nào để kiểm tra xem một tệp PDF có được gắn thẻ là Nội dung có cấu trúc của Adobe như bạn đã viết trong bài đăng trên blog của mình không? Cảm ơn bạn, –

+0

Bạn cần xem liệu các thẻ có hiện diện hay không. –

+0

Liên kết đó dường như đã chết. Bạn có một URL mới không? –

1

Tôi đã có một vấn đề tương tự và kết thúc bằng xpdf từ http://www.foolabs.com/xpdf/ Một trong những utils được PDFtoText, nhưng tôi đoán nó tất cả đi đến, làm thế nào PDF được sản xuất.

+1

Tôi đã thử một số phương pháp. Tôi đã sử dụng PyPDF và PDF Miner và thậm chí sử dụng Acrobat để lưu vào văn bản. Không ai trong số họ làm việc cũng như pdftotext của xpdf bằng cách sử dụng tùy chọn -layout. Tôi sẽ không bận tâm với bất cứ điều gì khác. – chrisfs

1
$ pdftotext -layout thingwithtablesinit.pdf 

sẽ tạo một tệp văn bản thingwithtablesinit.txt với bảng bên phải.

0

Như được giải thích trong các câu trả lời khác, việc trích xuất văn bản từ PDF không phải là một tác vụ chuyển tiếp thẳng. Tuy nhiên, có một số thư viện Python nhất định như pdfminer (pdfminer3k cho Python 3) có hiệu quả hợp lý.

Đoạn mã dưới đây cho thấy một lớp Python có thể được khởi tạo để trích xuất văn bản từ PDF. Điều này sẽ làm việc trong hầu hết các trường hợp.

(nguồn - https://gist.github.com/vinovator/a46341c77273760aa2bb)

# Python 2.7.6 
# PdfAdapter.py 

""" Reusable library to extract text from pdf file 
Uses pdfminer library; For Python 3.x use pdfminer3k module 
Below links have useful information on components of the program 
https://euske.github.io/pdfminer/programming.html 
http://denis.papathanasiou.org/posts/2010.08.04.post.html 
""" 


from pdfminer.pdfparser import PDFParser 
from pdfminer.pdfdocument import PDFDocument 
from pdfminer.pdfpage import PDFPage 
# From PDFInterpreter import both PDFResourceManager and PDFPageInterpreter 
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter 
# from pdfminer.pdfdevice import PDFDevice 
# To raise exception whenever text extraction from PDF is not allowed 
from pdfminer.pdfpage import PDFTextExtractionNotAllowed 
from pdfminer.layout import LAParams, LTTextBox, LTTextLine 
from pdfminer.converter import PDFPageAggregator 
import logging 

__doc__ = "eusable library to extract text from pdf file" 
__name__ = "pdfAdapter" 

""" Basic logging config 
""" 
log = logging.getLogger(__name__) 
log.addHandler(logging.NullHandler()) 


class pdf_text_extractor: 
    """ Modules overview: 
    - PDFParser: fetches data from pdf file 
    - PDFDocument: stores data parsed by PDFParser 
    - PDFPageInterpreter: processes page contents from PDFDocument 
    - PDFDevice: translates processed information from PDFPageInterpreter 
     to whatever you need 
    - PDFResourceManager: Stores shared resources such as fonts or images 
     used by both PDFPageInterpreter and PDFDevice 
    - LAParams: A layout analyzer returns a LTPage object for each page in 
     the PDF document 
    - PDFPageAggregator: Extract the decive to page aggregator to get LT 
     object elements 
    """ 

def __init__(self, pdf_file_path, password=""): 
    """ Class initialization block. 
    Pdf_file_path - Full path of pdf including name 
    password = If not passed, assumed as none 
    """ 
    self.pdf_file_path = pdf_file_path 
    self.password = password 

def getText(self): 
    """ Algorithm: 
    1) Txr information from PDF file to PDF document object using parser 
    2) Open the PDF file 
    3) Parse the file using PDFParser object 
    4) Assign the parsed content to PDFDocument object 
    5) Now the information in this PDFDocumet object has to be processed. 
    For this we need PDFPageInterpreter, PDFDevice and PDFResourceManager 
    6) Finally process the file page by page 
    """ 

    # Open and read the pdf file in binary mode 
    with open(self.pdf_file_path, "rb") as fp: 

     # Create parser object to parse the pdf content 
     parser = PDFParser(fp) 

     # Store the parsed content in PDFDocument object 
     document = PDFDocument(parser, self.password) 

     # Check if document is extractable, if not abort 
     if not document.is_extractable: 
      raise PDFTextExtractionNotAllowed 

     # Create PDFResourceManager object that stores shared resources 
     # such as fonts or images 
     rsrcmgr = PDFResourceManager() 

     # set parameters for analysis 
     laparams = LAParams() 

     # Create a PDFDevice object which translates interpreted 
     # information into desired format 
     # Device to connect to resource manager to store shared resources 
     # device = PDFDevice(rsrcmgr) 
     # Extract the decive to page aggregator to get LT object elements 
     device = PDFPageAggregator(rsrcmgr, laparams=laparams) 

     # Create interpreter object to process content from PDFDocument 
     # Interpreter needs to be connected to resource manager for shared 
     # resources and device 
     interpreter = PDFPageInterpreter(rsrcmgr, device) 

     # Initialize the text 
     extracted_text = "" 

     # Ok now that we have everything to process a pdf document, 
     # lets process it page by page 
     for page in PDFPage.create_pages(document): 
      # As the interpreter processes the page stored in PDFDocument 
      # object 
      interpreter.process_page(page) 
      # The device renders the layout from interpreter 
      layout = device.get_result() 
      # Out of the many LT objects within layout, we are interested 
      # in LTTextBox and LTTextLine 
      for lt_obj in layout: 
       if (isinstance(lt_obj, LTTextBox) or 
         isinstance(lt_obj, LTTextLine)): 
        extracted_text += lt_obj.get_text() 

    return extracted_text.encode("utf-8") 

Lưu ý - Có thư viện khác như PyPDF2 mà là tốt ở việc chuyển đổi một PDF, chẳng hạn như việc sáp nhập các trang PDF, tách hoặc cắt xén các trang cụ thể ra khỏi PDF vv

Các vấn đề liên quan