You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python语音助手代码出现NoneType错误,指定字符串类型无效

问题解决:Python语音助手NoneType错误

问题根源

你的代码触发NoneType错误的核心原因有两个:

  1. take_command函数没有返回处理后的语音指令:即使语音识别成功生成了command变量,函数执行完try块后没有返回该变量,默认返回None
  2. 异常捕获后直接pass:语音识别失败(比如听不到声音、识别出错)时,函数依然返回None,后续执行'play' in command这类字符串操作时,就会因为command是None而报错

修复方案

步骤1:给take_command添加返回值

确保函数无论成功还是失败,都返回字符串类型的值,避免返回None:

  • 识别成功时,返回处理后的command
  • 识别失败时,返回空字符串""

步骤2:优化run_alexa的输入判断

提前判断command是否有效,避免无效输入进入后续分支

修改后的完整代码

import pyttsx3
import speech_recognition as sr
import pywhatkit
import datetime
import wikipedia
import pyjokes

def talk(text):
    engine.say(text)
    engine.runAndWait()

listener = sr.Recognizer()
engine = pyttsx3.init()

def take_command():
    try:
        with sr.Microphone() as source:
            talk('listening')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            command = command.replace('alexa', '')
            talk(command)
            return command  # 添加返回指令
    except:
        talk("Sorry, I didn't catch that")
        return ""  # 异常时返回空字符串

def run_alexa():
    command = take_command()
    print(command)
    # 先判断指令是否有效
    if not command:
        talk('say that again please')
        return
    if 'play' in command:
        song = command.replace('play','').strip()  # 去掉多余空格
        pywhatkit.playonyt(song)
        talk(f'playing {song}')
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%H:%M %p')  # 优化时间格式
        talk(f'the time is {time}')
    elif 'search' in command:
        person = command.replace('search','').strip()
        try:
            info = wikipedia.summary(person, 2)
            talk(info)
            print(info)
        except wikipedia.exceptions.DisambiguationError:
            talk("There are multiple results, please be more specific")
        except wikipedia.exceptions.PageError:
            talk("I couldn't find information about that")
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    elif 'google' in command:
        google_query = command.replace('google','').strip()
        pywhatkit.search(google_query)
        talk(f'searching for {google_query}')
    else:
        talk('say that again please')

额外优化说明

  • 给字符串替换后的结果加strip(),去掉多余的前后空格,避免执行操作时传入无效内容
  • 给wikipedia查询添加异常捕获,处理找不到页面或歧义词条的情况
  • 用f-string替代字符串拼接,代码更简洁易读

内容的提问来源于stack exchange,提问作者Axxor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:20:35