Python讀取pdf文件的簡單代碼示例
安裝命令
需要安裝操作pdf的三方類庫,命令如下:
pip install pdfminer3K
安裝過程如下:

引入類庫
需要引入很多的類庫。
示例如下:
import sys import importlib importlib.reload(sys) from pdfminer.pdfparser import PDFParser, PDFDocument from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LTTextBoxHorizontal, LAParams from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
讀取pdf實現(xiàn)
實現(xiàn)步驟為:先通過二進(jìn)制方式打開測試pdf文檔,創(chuàng)建pdf文檔解析測試文檔內(nèi)容,
最后讀取文件內(nèi)容,保存到另一個文件中。
示例如下:
import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import os
def read_pdf(path, toPath):
# 以二進(jìn)制方式打開pdf文件
f = open(path, 'rb')
# 創(chuàng)建一個pdf文檔分析器
parser = PDFParser(f)
# 創(chuàng)建pdf文檔
pdfFile = PDFDocument()
# 鏈接分析器與文檔對象
parser.set_document(pdfFile)
pdfFile.set_parser(parser)
# 提供初始化密碼
pdfFile.initialize()
# 檢測文檔是否提供txt轉(zhuǎn)換
if not pdfFile.is_extractable:
raise PDFTextExtractionNotAllowed
else:
# 解析數(shù)據(jù)
# 數(shù)據(jù)管理器
manager = PDFResourceManager()
# 創(chuàng)建一個PDF設(shè)備對象
laparams = LAParams()
device = PDFPageAggregator(manager, laparams=laparams)
# 解釋器對象
interpreter = PDFPageInterpreter(manager, device)
for page in pdfFile.get_pages():
interpreter.process_page(page)
layout = device.get_result()
for x in layout:
if isinstance(x, LTTextBoxHorizontal):
with open(toPath, 'a', encoding='utf-8') as f:
print(x.get_text())
f.write(x.get_text() + "\n")
path = os.path.join(os.getcwd(), 'test_1.pdf')
toPath = os.path.join(os.getcwd(), 'test_2.txt')
read_pdf(path, toPath)注意:無法讀取中文,貌似需要加載中文字體。還有就是在寫入pdf文件,格式不對無法打開暫時沒找到原因。
附:python讀取PDF文件并做詞云可視化
import pdfplumber # 導(dǎo)入庫
import jieba
from wordcloud import WordCloud
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
# 用pdf文件解析器讀取文件
with pdfplumber.open('中華文化.pdf') as f:
# 用for循環(huán)讀取文件中的每一頁
for page in f.pages:
text = page.extract_text()
txt_f = open(r'中華文化.txt', mode='a', encoding='utf-8') # 創(chuàng)建txt文件
txt_f.write(text) # 寫入txt文件
file = open('中華文化.txt',encoding='utf-8')
file = file.read() #讀取txt文件
txtlist = jieba.lcut(file)
string = " ".join(txtlist)
stop_words = {}
counts = {}
for txt in txtlist:
if len(txt) == 1:
stop_words[txt] = stop_words.get(txt, 0) + 1
else:
counts[txt] = counts.get(txt, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
y1 = []
labels = []
for i in range(1,10):
y1.append(items[i][1])
labels.append(items[i][0])
# plt.figure(figsize=(8,4))
width = 0.3
x = np.arange(len(y1))
a = [i for i in range(0,9)]
plt.xticks(a,labels,rotation = 30)
plt.bar(x=x,height=y1,width=width)
plt.title('PDF文件中熱詞統(tǒng)計分析')
plt.savefig("熱詞統(tǒng)計分析.png")
plt.show()
print("-------熱詞統(tǒng)計分析完成!-------")
stoplist=[]
item = list(stop_words.items())
for i in range(len(item)):
txt,count = item[i]
stoplist.append(txt)
#print(stoplist)
setlist = set(stoplist)
wcd = WordCloud(width=1000, height=700, background_color='white', font_path='msyh.ttc', scale=15, stopwords=setlist)
wcd.generate(string)
wcd.to_image()
print("-------熱詞詞云生成完成!-------")
wcd.to_file('詞云.png') # 導(dǎo)出圖片總結(jié)
本篇只是使用Python 實現(xiàn)讀取pdf文件簡單示例,因為時間關(guān)系沒有做深入的擴(kuò)展,等之后有時間再做補(bǔ)充。
到此這篇關(guān)于Python讀取pdf文件的文章就介紹到這了,更多相關(guān)Python讀取pdf文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用Python判斷應(yīng)用是否處于已打包狀態(tài)
在使用 PyInstaller 打包 Python 應(yīng)用時,有時需要在代碼中判斷程序是否處于“打包狀態(tài)”,本文將介紹幾種方法來判斷是否處于打包狀態(tài),感興趣的可以了解下2025-03-03
解讀sqlalchemy的常用數(shù)據(jù)類型有哪些
這篇文章主要介紹了解讀sqlalchemy的常用數(shù)據(jù)類型有哪些,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
python爬蟲將js轉(zhuǎn)化成json實現(xiàn)示例
這篇文章主要為大家介紹了python爬蟲將js轉(zhuǎn)化成json實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
tensorflow之自定義神經(jīng)網(wǎng)絡(luò)層實例
今天小編就為大家分享一篇tensorflow之自定義神經(jīng)網(wǎng)絡(luò)層實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
PyQt5連接MySQL及QMYSQL driver not loaded錯誤解決
這篇文章主要介紹了PyQt5連接MySQL及QMYSQL driver not loaded錯誤解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
解決pytorch報錯:AssertionError: Invalid device id的問題
今天小編就為大家分享一篇解決pytorch報錯:AssertionError: Invalid device id的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python+Matplotlib繪制發(fā)散條形圖的示例代碼
發(fā)散條形圖(Diverging Bar)是一種用于顯示數(shù)據(jù)分布的圖表,可以幫助我們比較不同類別或分組的數(shù)據(jù)的差異和相對性,本文介紹了Matplotlib繪制發(fā)散條形圖的函數(shù)源碼,需要的可以參考一下2023-06-06

