Python gTTS不接受变量中的字符串

时间:2016-11-18 03:02:39

标签: python

我正在编写一个python脚本来扫描包含google vision OCR文本的照片,然后使用Google gTTS来说出文本。这是代码:

#BookrBasic

from os import system
from time import sleep
from pygame import mixer
from gtts import gTTS
import subprocess


def tts(speech):
tts = gTTS(text=speech, lang='en')
tts.save("/tmp/text.mp3")
subprocess.Popen(['mpg123', '-q', '/tmp/text.mp3']).wait()

def ocr(file):
out = system('python3 ~/bookrbasic/ocr.py <KEY GOES HERE> ' + file)
return out

text = ocr("~/bookrbasic/photos/canada4.jpg")
tts(text)

这是我收到的错误:

Traceback (most recent call last):
  File "BookrBasic.py", line 20, in <module>
    tts(text)
  File "BookrBasic.py", line 11, in tts
    tts = gTTS(text=speech, lang='en')
  File "/usr/local/lib/python2.7/dist-packages/gtts/tts.py", line 72, in     __init__
    raise Exception('No text to speak')
Exception: No text to speak

有谁知道这里的问题是什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

没关系,我设法通过写入tmp中的文件来修复它。

以下是新代码,以防任何人遇到类似问题:

#BookrBasic

import os 
from os import system
from time import sleep
from pygame import mixer
from gtts import gTTS
import subprocess


def tts(speech):
    tts = gTTS(text=speech, lang='en-uk')
    os.mkfifio('/tmp/fifo')
    tts.save("/tmp/text.mp3")
    subprocess.Popen(['mpg123', '-q', '/tmp/text.mp3']).wait()


def ocr(file):
    system('python3 ~/bookrbasic/ocr.py <KEY GOES HERE> ' + file + ' > /tmp/text.txt')
    with open ("/tmp/text.txt", "r") as myfile:
        out=myfile.read()
    return out

text = ocr("~/bookrbasic/photos/canada4.jpg")
tts(text)