每次我运行旨在构建弱Ai平台的代码时,都会收到 AttributeError:'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")
或者,麦克风也没有接听输入,为什么会出现这种情况?
答案 0 :(得分:1)
该错误是因为变量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")
答案 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-in')
print(f"user said: {query}\n")
except Exception as e:
print("Sorry i didn't catch that...")
return query
别忘了标记我的回答是否对您有帮助
答案 2 :(得分:0)
我正在尝试帮助您,但是我没有您要做什么的背景,但我将举一个例子:
wishMe()
query = takeCommand()
#Logic
if query:
# an then you can check your condition
query.lower()
答案 3 :(得分:0)
您需要添加takeCommand
函数的返回类型...然后
query=takeCommand
函数可以正常工作,否则它会向您返回错误(无类型)
因此,请在return query
函数中添加takeCommand
并尝试
我希望它将对您有帮助
谢谢