首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Gtts助手

Python Gtts助手
EN

Stack Overflow用户
提问于 2020-12-08 08:44:12
回答 1查看 172关注 0票数 0

我已经使用这个网站上的教程为Python语言编写了一个简单的助手代码:https://randerson112358.medium.com/build-a-virtual-assistant-using-python-2b0f78e68b94。创建者的代码是错误的,我已经修复了一些缩进错误。不过,它还有其他一些错误,我想要修复这些错误。

错误,例如:

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\Johann\Desktop\BIZ\Python\BoringAuto1.py", line 120, in <module>
    assistantResponse(response)
  File "C:\Users\Johann\Desktop\BIZ\Python\BoringAuto1.py", line 33, in assistantResponse
    myobj = gTTS(text=text, lang="en", slow=False)
  File "C:\Users\Johann\AppData\Local\Programs\Python\Python39\lib\site-packages\gtts\tts.py", line 126, in __init__
    assert text, 'No text to speak'
AssertionError: No text to speak

如果你能帮我一把,那就太棒了。代码如下:

代码语言:javascript
复制
import speech_recognition as sr
import os
import datetime
import warnings
import calendar
from gtts import gTTS
import random
import wikipedia

warnings.filterwarnings('ignore')

def recordAudio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)

    data = ""
    try:
        data = r.recognize_google(audio)
        print("You said:  " + data)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand")
    except sr.RequestError as e:
        print("Request error from Google Speech Recognition")
    return data



def assistantResponse(text):
    print(text)

    myobj = gTTS(text=text, lang="en", slow=False)

    myobj.save("assistant_response.mp3")

    os.system("start assistant_response.mp3")

def wakeWord(text):
    WAKE_WORDS = ["hey computer", "okay boomer"]
    text = text.lower()

    for phrase in WAKE_WORDS:
        if phrase in text:
            return True

    return False



def getDate():
    
    now = datetime.datetime.now()
    my_date = datetime.datetime.today()
    weekday = calendar.day_name[my_date.weekday()]
    monthNum = now.month
    dayNum = now.day
    month_names = ['January', 'February', 'March', 'April', 'May',
       'June', 'July', 'August', 'September', 'October', 'November',   
       'December']
    ordinalNumbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', 
                      '7th', '8th', '9th', '10th', '11th', '12th',                      
                      '13th', '14th', '15th', '16th', '17th', 
                      '18th', '19th', '20th', '21st', '22nd', 
                      '23rd', '24th', '25th', '26th', '27th', 
                      '28th', '29th', '30th', '31st']
   
    return 'Today is ' + weekday + ' ' + month_names[monthNum - 1] + ' the ' + ordinalNumbers[dayNum - 1] + '.'


def greeting(text):
    GREETING_INPUTS = ["hi", "trump", "wassup"]
    GREETING_RESPONSES = ["howdy", "hola", "eyo", "wassup bro"]
    for word in text.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES) + '.'
    return ""


def getPerson(text):
    wordList = text.split()

    for i in range(0, len(wordList)):
        if i + 3 <= len(wordList) - 1 and wordList[i].lower() == 'who' and wordList[i + 1].lower() == 'is':
            return wordList[i + 2] + ' ' + wordList[i + 3]
a = 0
while a < 10:
    text = recordAudio()
    response = ""

    if (wakeWord(text) == True):
        response = response + greeting(text)

        if ("date" in text):
            get_date = getDate()
            response = response + "" + get_date

        if ("time" in text):
            now = datetime.datetime.now()
            meridiem = ""
            if now.hour >= 12:
                meridiem = "p.m."
                hour = now.hour - 12
            else:
                meridiem = "a.m."
                hour = now.hour

            if now.minute < 10:
                    minute = "0"+str(now.minute)
            else:
                minute = str(now.minute)
                        
            response = response + ' '+ 'It is '+ str(hour)+ ':'+minute+' '+meridiem+' .'

    if ("who is" in text):
        person = getPerson(text)
        wiki = wikipedia.summary(person, sentences=2)
        response = response + "" + wiki

    assistantResponse(response)

提前感谢!

致以最好的问候,约翰

EN

回答 1

Stack Overflow用户

发布于 2021-01-31 13:05:55

首先,在发言之前,请检查是否有要发言的文本:

代码语言:javascript
复制
if response != "":
  assistantResponse(response)

其次,您可以将“who is”函数包装在try except块中,以捕获“未找到”错误。

代码语言:javascript
复制
def getPerson(text):
  wordList = text.split()
  for i in range(0, len(wordList)):
    if i + 3 <= len(wordList) - 1 and wordList[i].lower() == 'who' and wordList[i + 1].lower() == 'is':
      return wordList[i + 2] + ' ' + wordList[i + 3]
  return ""
if 'who is' in text:
  person = getPerson(text)
  if person != "":
    wiki = wikipedia.summary(person, sentences=2)
    response += wiki
  else:
    response += "I could not find the person you were looking for"

这应该会捕获我在测试您的程序时遇到的所有错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65191520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档