How Python parses and reads the contents of a PDF file

Source: Internet
Author: User
This article mainly introduces the method of Python parsing and reading the contents of PDF file, and describes the relevant operation skills of Python2.7 to read PDF in Win32 and Win64 environment, according to the example form, and the friends can refer to the following

This example describes how Python parses and reads the contents of a PDF file. Share to everyone for your reference, as follows:

First, the problem description

Use Python to read PDF text content.

Second, the effect

Third, the operating environment

python2.7

Iv. libraries that need to be installed

Pip Install Pdfminer

V. Realization of source Code

Code 1 (Win64)

# Coding=utf-8import sysreload (SYS) sys.setdefaultencoding (' utf-8 ') import timetime1=time.time () Import Os.pathfrom Pdfminer.pdfparser Import pdfparser,pdfdocumentfrom pdfminer.pdfinterp import Pdfresourcemanager, Pdfpageinterpreterfrom pdfminer.converter Import pdfpageaggregatorfrom pdfminer.layout import LTTextBoxHorizontal, Laparamsfrom pdfminer.pdfinterp Import Pdftextextractionnotallowedresult=[]class Cpdf2txtmanager (): Def __init__ ( Self): "Constructor" Def changepdftotext (Self, filePath): File = open (path, ' RB ') # opened in binary read mode #用文件 object to create a PDF document Parser Praser = pdfparser (file) # Create a PDF document DOC = Pdfdocument () # The Connection analyzer and the Document Object Praser.set_document (  Doc) Doc.set_parser (praser) # provides initialization password # creates an empty string without a password doc.initialize () # Detects if the document provides a TXT conversion, ignores if not    Doc.is_extractable:raise pdftextextractionnotallowed # Create PDF Explorer to manage shared resources Rsrcmgr = Pdfresourcemanager () # Create a PDF device Object laparams = Laparams () device = Pdfpageaggregator (rsrcMgr, Laparams=laparams) # Create a PDF interpreter Object interpreter = Pdfpageinterpreter (rsrcmgr, device) pdfstr = ' # Loop through the list, Each time a page is processed for the page in Doc.get_pages (): # doc.get_pages () Gets the page list Interpreter.process_page (page) # accepts the Ltpage Object layout = Device.get_result () for x in Layout:if hasattr (x, "Get_text"): # Print X.get_ Text () Result.append (X.get_text ()) FileNames = Os.path.splitext (FilePath) with open (filenames[0 ] + ' txt ', ' WB ') as F:results = X.get_text () print (results) f.write (results + ' \ n ') if __ name__ = = ' __main__ ': ' Parse PDF text, save to TXT file ' path = U ' c:/data3.pdf ' Pdf2txtmanager = Cpdf2txtmanager () pdf2tx  Tmanager.changepdftotext (path) # print result[0] time2 = Time.time () print u ' OK, parse pdf end! ' Print U ' total time: ' + str (time2-time1) + ' s '

Code 2 (WIN32)

# Coding=utf-8import sysreload (SYS) sys.setdefaultencoding (' utf-8 ') import timetime1=time.time () Import Os.pathfrom Pdfminer.pdfinterp import Pdfresourcemanager, pdfpageinterpreterfrom pdfminer.converter import PDFPageAggregatorfrom Pdfminer.layout Import laparamsfrom pdfminer.pdfpage import pdftextextractionnotallowedfrom pdfminer.pdfparser Import Pdfparserfrom pdfminer.pdfdocument Import pdfdocumentfrom pdfminer.pdfpage import Pdfpageresult=[]class Cpdf2txtmanager (): Def __init__ (self): "Constructor" Def changepdftotext (Self, filePath): File = Ope    N (Path, ' RB ') # opens in binary read mode #用文件对象来创建一个pdf文档分析器 praser = pdfparser (file) # Create a PDF document DOC = Pdfdocument (praser)    # Detects if document provides TXT conversion, does not provide ignore if not doc.is_extractable:raise pdftextextractionnotallowed # create PDF Explorer to manage shared resources Rsrcmgr = Pdfresourcemanager () # Creates a PDF device Object laparams = Laparams () device = Pdfpageaggregator (Rsrcmgr, laparams=l Aparams) # Create a PDF interpreter Object interpreter = PdfpageinterpretER (rsrcmgr, device) Pdfstr = "# loops through the list, processing one page at a time for page in Pdfpage.create_pages (DOC): # doc.get_pages () won        Fetch page List interpreter.process_page (page) # accepts the page's Ltpage object layout = Device.get_result () for X in Layout: If Hasattr (x, "Get_text"): # Print X.get_text () result.append (X.get_text ()) FileNames =            Os.path.splitext (FilePath) with open (Filenames[0] + ' txt ', ' WB ') as F:results = X.get_text () Print (results) f.write (results + ' \ n ') if __name__ = = ' __main__ ': "' parse PDF text, save to TXT file ' path = U ' C:/36.pdf ' Pdf2txtmanager = Cpdf2txtmanager () pdf2txtmanager.changepdftotext (path) # print result[0] time2 = Time.time  () print U ' OK, parse pdf end! ' Print U ' total time: ' + str (time2-time1) + ' s '

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.