设计思路:首先通过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'))