![](/img/trans.png)
[英]TypeError: argument of type 'NoneType' is not iterable need a fix
[英]How to fix 'TypeError: argument of type 'NoneType' is not iterable ' in python
我正在使用 pyttsx3 和 SpeechRecognition 为虚拟助手构建 VUI 作为爱好项目。 我首先制作了一个名为take_order()
的 function 然后在下一个 function run_agos()
我检查了take_Order()
是否包含一些关键字来启动另一个进程,请参见以下代码:
import speech_recognition as sr
import pywhatkit
import datetime
import winsound
import wikipedia
import pyjokes
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init()
def talk(text):
engine.say(text)
engine.runAndWait()
def take_order():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alex' in command:
command = command.replace('alexa', '')
print(command)
else:
return
return command
except pass
def run_agos():
task = take_order()
if 'play' in task:
song = task.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in task:
time = datetime.datetime.now().strftime('%I:%M %p')
print(time)
talk('Current time is ' + time)
elif 'who is' in task:
person = task.replace('who is', '')
try:
info = wikipedia.summary(person, 1)
print(info)
talk(info)
except wikipedia.exceptions.DisambiguationError as e:
print(e.options)
talk(person + 'may refer to')
talk(e.options)
elif 'what is' in task:
thing = task.replace('what is', '')
try:
info = wikipedia.summary(thing, 1)
print(info)
talk(info)
except wikipedia.exceptions.DisambiguationError as e:
print(e.options)
talk(thing + 'may refer to')
talk(e.options)
elif 'joke' in task:
joke = pyjokes.get_joke()
talk(joke)
print(joke)
else:
talk('I did not hear that, pleas repeat the command.')
return run_agos()
while True:
run_agos()
起初它工作正常,但过了一会儿我得到TypeError: argument of type 'NoneType' is not iterable
并且程序关闭。 我还得到了退出代码:-1073741819 (0xC0000005)。如何修复此错误,使其继续运行程序?
看起来在 take_order function 中,您要么在发生错误时不返回任何内容,要么在命令中没有“alexa”时也不返回任何内容。 然后您的代码检查if 'play' in task
。 在这里,任务是无,因为没有返回任何内容。 这是你的主要问题。 我建议返回一个特定的字符串或一个值,例如 -1。 然后,在task = take_order()
之后,检查 task 是否是那个值。 例如
def take_order():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alex' in command:
command = command.replace('alexa', '')
print(command)
else:
return -1
return command
except: return -1
def run_agos():
task = take_order()
if task == -1: return
...
还有一件事:你总是在 run_agos() 的末尾return run_agos()
,它递归地调用自己。 这是不好的做法,因为您已经有一个while True
循环永远调用 function。 我建议删除run_agos
末尾的 return 语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.