Python là ngôn ngữ đa dụng vì cung cấp bộ thư viện khổng lồ cho nhiều nhu cầu. Chúng ta đều làm việc với file Portable Document Format (PDF). Python cung cấp nhiều cách làm việc với PDF. Ở đây ta sẽ dùng thư viện PyPDF2.
PyPDF2 là thư viện PDF thuần Python có khả năng tách, gộp, cắt và biến đổi trang PDF. Nó cũng có thể thêm dữ liệu tùy chỉnh, tùy chọn xem, mật khẩu vào file PDF. Nó trích xuất text và metadata từ PDF cũng như gộp toàn bộ file.
Vì có thể làm nhiều thao tác trên PDF với PyPDF2, nó giống như con dao đa năng (Swiss-army knife).
Bắt đầu
Vì PyPDF2 là package Python chuẩn, cần cài đặt. Việc cài rất dễ, dùng pip. Chạy lệnh sau trên terminal:
C:\Users\rajesh>pip install pypdf2 Collecting pypdf2 Downloading https://files.pythonhosted.org/packages/b4/01/68fcc0d43daf4c6bdbc6b33cc3f77bda531c86b174cac56ef0ffdb96faab/PyPDF2-1.26.0.tar.gz (77kB) 100% |████████████████████████████████| 81kB 83kB/s Building wheels for collected packages: pypdf2 Building wheel for pypdf2 (setup.py) ... done Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\53\84\19\35bc977c8bf5f0c23a8a011aa958acd4da4bbd7a229315c1b7 Successfully built pypdf2 Installing collected packages: pypdf2 Successfully installed pypdf2-1.26.0
Để kiểm tra, import pypdf2 từ Python shell:
>>> import PyPDF2 >>> Successful, Great.
Trích xuất Metadata
Có thể trích xuất dữ liệu hữu ích từ bất kỳ PDF nào. Ví dụ: tác giả, tiêu đề, chủ đề, số trang.
Chương trình Python trích xuất thông tin từ PDF dùng PyPDF2:
from PyPDF2 import PdfFileReader def extract_pdfMeta(path): with open(path, 'rb') as f: pdf = PdfFileReader(f) info = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() print("Author: \t", info.author) print() print("Creator: \t", info.creator) print() print("Producer: \t",info.producer) print() print("Subject: \t", info.subject) print() print("title: \t",info.title) print() print("Number of Pages in pdf: \t",number_of_pages) if __name__ == '__main__': path = 'DeepLearning.pdf' extract_pdfMeta(path) Kết quả
Author: Nikhil Buduma,Nicholas Locascio Creator: AH CSS Formatter V6.2 MR4 for Linux64 : 6.2.6.18551 (2014/09/24 15:00JST) Producer: Antenna House PDF Output Library 6.2.609 (Linux64) Subject: None title: Fundamentals of Deep Learning Number of Pages in pdf: 298
Bिना mở file PDF, ta đã lấy được thông tin hữu ích.
Trích xuất Text từ PDF
Có thể trích xuất text từ PDF. Tuy nhiên hỗ trợ tích hợp trích xuất ảnh hạn chế.
Thử trích xuất text từ trang cụ thể (ví dụ: trang 50) của file PDF trên.
# Import pypdf2 from PyPDF2 import PdfFileReader def extract_pdfText(path): with open(path, 'rb') as f: pdf = PdfFileReader(f) # lấy trang 50 page = pdf.getPage(50) print(page) print('Page type: {}'.format(str(type(page)))) # Trích xuất text từ trang 50 text = page.extractText() print(text) if __name__ == '__main__': path = 'DeepLearning.pdf' extract_pdfText(path) Kết quả
{'/Annots': IndirectObject(1421, 0), '/Contents': IndirectObject(179, 0), '/CropBox': [0, 0, 595.3, 841.9], '/Group': {'/CS': '/DeviceRGB', '/S': '/Transparency', '/Type': '/Group'}, '/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4863, 0), '/Resources': IndirectObject(1423, 0), '/Rotate': 0, '/Type': '/Page' } Page type: <class 'PyPDF2.pdf.PageObject'> time. In inverted dropout, any neuron whose activation hasn†t been silenced has its output divided by p before the value is propagated to the next layer. With this fix, Eoutput=p⁄xp+1ƒ p⁄0= x, and we can avoid arbitrarily scaling neuronal output at test time. SummaryIn this chapter, we†ve learned all of the basics involved in training feed-forward neural networks. We†ve talked about gradient descent, the backpropagation algorithm, as well as various methods we can use to prevent overfitting. In the next chapter, we†ll put these lessons into practice when we use the TensorFlow library to efficiently implement our first neural networks. Then in Chapter 4 , we†ll return to the problem of optimizing objective functions for training neural networks and design algorithmsto significantly improve performance. These improvements will enable us to process much more data, which means we†ll be able to build more comprehensive models. Summary | 37 Mặc dù lấy được text từ trang 50 nhưng không sạch. Rất tiếc, PyPDF2 hỗ trợ trích xuất text rất hạn chế.
Xoay trang cụ thể của file PDF
>>> import PyPDF2 >>> deeplearningFile = open('DeepLearning.pdf', 'rb') >>> pdfReader = PyPDF2.PdfFileReader(deeplearningFile) >>> page = pdfReader.getPage(0) >>> page.rotateClockwise(90) { '/Contents': [IndirectObject(4870, 0), IndirectObject(4871, 0), IndirectObject(4872, 0), IndirectObject(4873, 0), IndirectObject(4874, 0), IndirectObject(4875, 0), IndirectObject(4876, 0), IndirectObject(4877, 0)], '/CropBox': [0, 0, 595.3, 841.9], '/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4862, 0), '/Resources': IndirectObject(4889, 0), '/Rotate': 90, /Type': '/Page' } >>> pdfWriter = PyPDF2.PdfFileWriter() >>> pdfWriter.addPage(page) >>> resultPdfFile = open('rotatedPage.pdf', 'wb') >>> pdfWriter.write(resultPdfFile) >>> resultPdfFile.close() >>> deeplearningFile.close() Kết quả
