python音频 pdf_利用Python将. pdf电子书籍转换成音频有声读物

太好了。现在,我们将文件位置存储在filelocation变量中。

将文件转换为一个字符串

如前所述,要在Python中打开文件,我们只需要使用open()方法。但是我们还希望将pdf文件转换为常规文本。

为此,我们将使用一个名为pdftotext的库。

先安装:

sudo pip install pdftotext

然后:

from tkinter import Tkfrom tkinter.filedialog import askopenfilenameimport pdftotextTk().withdraw() # we don't want a full GUI, so keep the root window from appearingfilelocation = askopenfilename() # open the dialog GUIwith open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it fpdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable

如果您打印这个变量,您将得到一个字符串数组。每个字符串都是文件中的一行。要将它们全部存储到一个.mp3文件中,我们必须确保它们都存储为一个字符串。让我们循环这个数组并将它们全部添加到一个字符串中:

from tkinter import Tkfrom tkinter.filedialog import askopenfilenameimport pdftotextTk().withdraw() # we don't want a full GUI, so keep the root window from appearingfilelocation = askopenfilename() # open the dialog GUIwith open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it fpdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variablestring_of_text = ''for text in pdf:string_of_text += text

输出.mp3文件

现在,我们准备使用gTTS(谷歌文本到语音)库。我们所需要做的就是传递我们创建的字符串,将输出存储在一个变量中,然后使用save()方法将文件输出到计算机。

先安装:

sudo pip install gtts

然后:

from tkinter import Tkfrom tkinter.filedialog import askopenfilenameimport pdftotextfrom gtts import gTTSTk().withdraw() # we don't want a full GUI, so keep the root window from appearingfilelocation = askopenfilename() # open the dialog GUIwith open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it fpdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variablestring_of_text = ''for text in pdf:string_of_text += textfinal_file = gTTS(text=string_of_text, lang='en') # store file in variablefinal_file.save("Generated Speech.mp3") # save file to computer

就这么简单!快去拿你的pdf去尝试吧。

原文请点击文末阅读原文。

·END·

关注我们

打开Python新世界大门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值