设计思路:首先通过PyPDF2非标准库提供的接口函数将PDF文件中的文本提取出来,然后,再使用pyttsx3非标准库将文本转换为音频文件。
使用pip的方式安装两个非标准库PyPDF2、pyttsx3。
pip install PyPDF2 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install pyttsx3 -i https://pypi.tuna.tsinghua.edu.cn/simple/
将这两个需要使用到的非标准库导入到当前代码块中。
import pyttsx3 as tsx
import PyPDF2 as pdf
编写PDF文件读取函数并且返回text文本字符串。
def read_pdf_to_txt(pdf_file):
'''
读取PDF文件返回text文本
:param pdf_file: PDF文件路径
:return:
'''
reader = pdf.PdfFileReader(open(pdf_file, 'rb'))
texts = ''
for page_num in range(reader.numPages):
text = reader.getPage(page_num).extractText()
text = text.strip().replace('\n', ' ')
texts = texts + text
return texts
def to_video(text):
'''
文本转换为音频函数
:param text: 文本字符串
:return:
'''
sp = tsx.init()
sp.save_to_file(text, './vi.mp3')
sp.runAndWait()
sp.stop()
调用to_video函数完成音频文件的转换。
to_video(text=read_pdf_to_txt('./vi.pdf'))
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦