如何修复AttributeError: ‘NoneType’ object has no attribute ‘lower’?

每次我运行旨在构建弱人工智能平台的代码时,都会收到一个AttributeError: ‘NoneType’ object has no attribute ‘lower’错误,我完全不知道为什么,因为我在跟随的一个教程中它运行得很好。有人能指导我如何修复这个问题吗?我对Python还是相当新手。谢谢

import pyttsx3import speech_recognition as srimport datetimeimport wikipediaimport webbrowserimport osimport smtplibimport pythoncomprint("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()#Logicif '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")

另外,麦克风也无法拾取输入,您对这也是什么原因有任何想法吗?


回答:

这个错误是因为变量query有时是None。而你对其应用了.lower()函数,这个函数只能在str类型的对象上使用。

你可以通过将你的代码放在一个if循环中来控制这个问题,只有当query变量中有字符串时才运行。比如这样:

wishMe()query = takeCommand()#Logicif 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")

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注