本篇文章給大家分享的是有關如何利用Python將. pdf電子書籍轉換成音頻有聲讀物,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
有沒有發現一個生活中的現象,我們很少有時間去真正讀一些存放在電腦或者ipad上的pdf書籍。我們打算讀這些書,但從來沒有讀過。所以我們為什么不用Python把它們做成有聲書,一邊聽一邊做別的事情呢?
我們計劃Python腳本步驟是這樣的:
允許用戶選擇讀取一個.pdf文件
將文件內容轉換為一個字符串
輸出的mp3音頻文件
允許用戶選擇讀取一個.pdf文件
Python可以輕松地讀取文件。
我只需要使用open(“filelocation”,“rb”)在讀取模式下打開文件。但我不想每次使用代碼時都要將文件復制并粘貼到代碼目錄中。因此,為了使它更容易,我們將使用tkinter庫來打開一個讓我們選擇文件的接口:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
太好了?,F在,我們將文件位置存儲在filelocation變量中。
將文件轉換為一個字符串
如前所述,要在Python中打開文件,我們只需要使用open()方法。但是我們還希望將pdf文件轉換為常規文本。
為此,我們將使用一個名為pdftotext的庫。
先安裝:
sudo pip install pdftotext
然后:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
如果您打印這個變量,您將得到一個字符串數組。每個字符串都是文件中的一行。要將它們全部存儲到一個.mp3文件中,我們必須確保它們都存儲為一個字符串。讓我們循環這個數組并將它們全部添加到一個字符串中:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
string_of_text = ''
for text in pdf:
string_of_text += text
輸出.mp3文件
現在,我們準備使用gTTS(谷歌文本到語音)庫。我們所需要做的就是傳遞我們創建的字符串,將輸出存儲在一個變量中,然后使用save()方法將文件輸出到計算機。
先安裝:
sudo pip install gtts
然后:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
from gtts import gTTS
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
string_of_text = ''
for text in pdf:
string_of_text += text
final_file = gTTS(text=string_of_text, lang='en') # store file in variable
final_file.save("Generated Speech.mp3") # save file to computer
就這么簡單!快去拿你的pdf去嘗試吧。
以上就是如何利用Python將. pdf電子書籍轉換成音頻有聲讀物,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。