为什么我不断收到AttributeError:'NoneType'对象没有属性'lower'?

时间:2020-03-30 20:37:08

标签: python python-3.x speech-recognition speech-to-text

我正在使用类似于Siri和Cortana的弱Ai,但是我注意到我一直收到“ AttributeError:'NoneType'对象没有属性'lower'”,与此同时,这不是我的代码接我的查询,它总是打印出“对不起,我没听清楚”。有人对如何解决这个问题有任何想法吗?谢谢

错误:

if 'wikipedia' in query.lower():
AttributeError: 'NoneType' object has no attribute 'lower'

代码:

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

print("Initializing Karren")

MASTER = "Bob"

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].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?") # deliberately on not included for now

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...")
        query = None
    return query 

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


if 'wikipedia' in query.lower():
    speak("Searching wikipedia")
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences=2)
    speak(results)

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为takeCommand返回了NoneNone没有lower方法,因此您会收到此错误。

您可以做的一件事是记录有关引发takeCommand的异常的更多信息,该异常导致它进入except块,或者只是删除try块,因此该异常停止程序,然后读取回溯。

答案 1 :(得分:0)

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...")
    query = "None" # or whatever str
return query 

我自己试过了。在 Takecommand() 函数中,query = none,用字符串替换 none。原因是当您遇到错误时,Nonetype 没有降低属性,query = none 并且由于它不是 str 或其他什么,lower() 无法转换它。如上所述,这是解决此错误而不会再遇到任何错误的一种方法。测试响应。

Otherwsie 删除查询 = none