为什么我的语音识别平台无法通过查询打开Wikipedia?

问题描述 投票:0回答:1

但是,我正在构建像Siri这样的弱AI平台,每次运行代码时,都会在query()中收到“ if'wikipedia”:TypeError:“ NoneType”对象不可调用”,而不是打开Wikipedia。有人可以指导我解决此问题。谢谢

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import pythoncom

print("Initializing Assistant...")

MASTER = "Bob"

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)


def speak(text):
    engine.say(text)
    engine.runAndWait()


def wishMe():
    hour = int(datetime.datetime.now().hour)

    if hour >= 0 and hour < 12:
        speak("Good Morning" + MASTER)

    elif hour >= 12 and hour < 18:
        speak("Good Afternoon" + MASTER)
    else:
        speak("Good Evening" + MASTER)

   # speak("I am Karren. How may I assist you?")


def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-uk')
        print(f"user said: {query}\n")

    except Exception as e:
        print("Sorry i didn't catch that...")


speak("Initializing Assistant...")
wishMe()
query = takeCommand()

# Logic
if 'wikipedia' in query:
    speak('searching wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences=2)
python python-3.x speech-recognition speech-to-text
1个回答
0
投票

您的函数takeCommand不返回任何内容,这意味着它显式返回了None。因此,该行

if 'wikipedia' in query:

相当于

if 'wikipedia' in None:

这无效,将引发TypeError

相反,您可能希望从query返回takeCommand,但要成功进行语音识别,即:

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

    query = None
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-uk')
        print(f"user said: {query}\n")

    except Exception as e:
        print("Sorry i didn't catch that...")

    return query

然后,您可以在将其视为字符串之前检查是否具有有效的返回值:

query = takeCommand()

if query is None:
    # Report to user that their speech was not understood
    ...
else:
    # Process query
    if 'wikipedia' in query:
        # Do something with query
        ...
© www.soinside.com 2019 - 2024. All rights reserved.