一、Python讀取PDF文件內容
要讀取PDF文件內容,需要使用PyPDF2模塊。該模塊在Python 2和Python 3中的使用方式略有不同。
在Python 2中,使用以下代碼打開一個PDF文件,並打印其中文本內容。
import pyPdf
pdf = pyPdf.PdfFileReader(file('example.pdf', 'rb'))
content = ''
for i in range(0, pdf.getNumPages()):
content += pdf.getPage(i).extractText() + "\n"
print content.encode('utf8')
在Python 3中,PyPDF2模塊已經更新為使用PyPDF2庫,而不是pyPdf。
import PyPDF2
pdf = open('example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdf)
content = ''
for i in range(0, pdfReader.numPages):
content += pdfReader.getPage(i).extractText() + "\n"
print(content)
使用PyPDF2和其他Python標準庫,還可以輕鬆地將PDF轉換為其他格式,如HTML或Markdown。
二、Python讀取PDF文件查找關鍵字
要在PDF文件中查找關鍵字,可以先讀取文件內容,然後在其中查找。
import PyPDF2
pdf = open('example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdf)
content = ''
for i in range(0, pdfReader.numPages):
content += pdfReader.getPage(i).extractText() + "\n"
if 'keyword' in content:
print('The keyword was found.')
上述代碼可以在讀取PDF文件內容後,在整個文本中查找「keyword」關鍵字,並打印出相應的結果。
三、Python讀取PDF文件為空
有些PDF文件沒有內容,只有一些圖片,這通常被稱為圖像PDF。
可以使用如下代碼來檢測PDF文件是否為空:
import PyPDF2
pdf = open('empty.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdf)
if pdfReader.getNumPages() == 0:
print('The PDF file is empty.')
在讀取PDF文件時,只需檢查getNumPages()是否為0即可確定它是否為空。
四、Python讀取PDF文件中的文字和圖片
對於包含文本和圖片的PDF文件,可以使用Python的Pillow庫,將PDF文件中的圖像提取出來。
import PyPDF2
from PIL import Image
pdf = open('example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdf)
for i in range(0, pdfReader.getNumPages()):
page = pdfReader.getPage(i)
xObject = page['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
mode = 'RGB' if xObject[obj]['/ColorSpace'] == '/DeviceRGB' else 'P'
image = Image.frombytes(mode, size, data)
image.save(obj[1:] + '.png', 'PNG')
上述代碼將從文本和圖像中提取圖像,以利用Pillow庫,將圖像轉換為PNG文件並保存到硬盤。
五、Python讀取PDF文件中的二進制函數
在讀取PDF文件時,可以使用Python的二進制模式,讀取文件中的二進制函數。
with open('example.pdf', 'rb') as pdf_file:
pdf_byte_array = pdf_file.read()
# 執行二進制函數
但是,要執行二進制函數,需要了解PDF文件格式和底層操作系統。
六、Python讀取文件路徑
使用Python的os模塊,可以輕鬆地讀取PDF文件的文件路徑。
import os
path = os.getcwd() + '/example.pdf'
with open(path, 'rb') as pdf_file:
# 執行其他操作
上述代碼中,使用了os模塊中的getcwd()函數,獲取當前工作目錄,再通過字符串拼接,得到PDF文件的完整路徑。
七、Python批量讀取文件
批量讀取PDF文件時,需要使用Python的os庫和glob庫。
以下代碼可以讀取一個目錄下所有的PDF文件,並打印出它們的文件名:
import os
import glob
path = '/folder'
os.chdir(path)
for file in glob.glob('*.pdf'):
with open(file, 'rb') as pdf_file:
print('Reading file: ' + file)
對於更大的文件集合,可以使用多線程或多進程來加快讀取速度。
八、Python讀取記事本文件
用Python讀取記事本文件與讀取PDF文件類似,可以使用Python的標準文件讀取模式來讀取文本文件。
with open('example.txt', 'r') as file:
for line in file:
print(line)
上述代碼將打開名為「example.txt」的文本文件,並循環遍歷其中的每一行,並將其打印出來。
九、Python PDF文件操作
使用Python的ReportLab庫,可以創建PDF文檔、添加文本、圖像和表格,並進行PDF文件的其他常見操作。
以下是一個簡單的示例代碼,用於生成一個包含圖像和文本的PDF文檔:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Spacer
def generate_pdf(filename):
doc = SimpleDocTemplate(filename, pagesize=letter)
Story = []
im = Image('my_logo.png', 2*inch, 2*inch)
Story.append(im)
styles = getSampleStyleSheet()
Story.append(Spacer(1, 12))
ptext = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.'
Story.append(Paragraph(ptext, styles['Normal']))
doc.build(Story)
generate_pdf('example.pdf')
上述代碼將創建一個PDF文檔,其中包含一個名為「my_logo.png」的圖像和一些隨機文本。之後,用生成的PDF文件名filename生成PDF文檔,並保存在磁盤上。
結束語
綜上所述,Python作為一門豐富靈活的編程語言,可以輕鬆地讀取和操作PDF文件。無論您是從PDF文件中提取文本、查找關鍵字,或是生成自定義的PDF文件,Python都是一個不可或缺的工具。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/190849.html