How do i fix AttributeError: 'NoneType' object has no attribute 'lower'?

How do i fix AttributeError: 'NoneType' object has no attribute 'lower'?

每次我 运行 我的代码旨在构建一个弱 Ai 平台时,我都会收到 AttributeError: 'NoneType' object has no attribute 'lower',我完全不知道为什么它在教程中工作正常我是 following.can 有人请引导我解决这个问题,因为我是 python 的新手。谢谢

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

print("Initializing Bot")

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("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-in')
        print(f"user said: {query}\n")

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

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

#Logic

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


if 'open youtube' in query.lower():
    webbrowser.open("youtube.com")

或者,麦克风也没有拾取输入,请问您知道为什么会这样吗?

你的函数没有返回任何东西。例如:

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-in')
        print(f"user said: {query}\n")

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

如果对你有帮助,别忘了标记采纳我的回答

错误是因为变量query有时是None。并且您正在对其应用 .lower() 函数,该函数仅适用于 str 类型的对象。

您可以通过将代码放在 if 循环中来控制它,该循环仅在查询变量中有字符串时才运行。可能像这样:

wishMe()
query = takeCommand()

#Logic

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


    if 'open youtube' in query.lower():
        webbrowser.open("youtube.com")

我正在努力帮助你,但我不知道你想做什么,但我会给你一个例子:

wishMe()
query = takeCommand()

#Logic

if query:
# an then you can check your condition
query.lower()

您需要添加 return 类型的 takeCommand 函数...然后 query=takeCommand 函数可以工作,否则它可以返回一个错误只是 nonetype ... 所以,在 try 和 except

之后在 takeCommand 函数中添加 return query

希望对您有所帮助

谢谢