我是python的新手,所以如果我的问题过于简单或愚蠢,我深表歉意。我保证,在发帖之前我已经试过谷歌搜索了。
我有一个很大的文件(大约1100页(,我需要一个语音转MP3。我看到的所有TTS模块(GTTS等(都需要字符串,而不是文档。以下是我的核心问题:
-
这能一次完成吗?我必须把文件分成小块吗?
-
Python是这项工作的正确工具吗?
-
在以下代码的情况下,有没有办法用类似
Myfile = open(mydoc.txt)
的东西替换Myfile = string
?
(是的,我只是从网上复制粘贴了这个,但我保证我一直在自己玩。(
# to speech conversion
from gtts import gTTS
# This module is imported so that we can
# play the converted audio
import os
# The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks!'
# Language in which you want to convert
language = 'en'
# Passing the text and language to the engine,
# here we have marked slow=False. Which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
# Saving the converted audio in a mp3 file named
# welcome
myobj.save("welcome.mp3")
filepath = 'test.txt'
text = ''
with open(filepath) as fp:
line = fp.readline()
while line:
text += line.strip() + 'n'
line = fp.readline()
这里的代码是逐行读取文本文件,然后将其附加到"text"字符串变量中。从那里,您应该能够将它加载到gTTS中。加载或文件大小较大可能需要一些时间,但它应该可以工作。