如何修复属性错误:'NoneType'对象没有属性"较低"?



每次我运行旨在构建弱Ai平台的代码时,我都会收到一个属性错误:"NoneType"对象没有属性"lower">,我完全不知道为什么,因为它在我正在学习的教程中运行良好。有人能帮我解决这个问题吗,因为我对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")

或者,麦克风也不会接收输入,有什么想法吗?

错误是因为变量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")

函数不会返回任何内容。例如:

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 

如果我的回答对你有帮助,别忘了标记为已接受

我试图帮助你,但我不知道你想做什么,但我会给你一个例子:

wishMe()
query = takeCommand()
#Logic
if query:
# an then you can check your condition
query.lower()

您需要添加takeCommand函数的返回类型。。。然后query=takeCommand函数可以工作,否则它会返回一个非类型的错误。。。因此,在尝试后,在takeCommand函数中添加return query,但除外

我希望它能帮助你

感谢

相关内容

  • 没有找到相关文章

最新更新