Python语音助手语音转文本无法匹配if语句问题求助
个人助手Harvey语音识别匹配问题
我用Python开发了名为Harvey的个人助手,跟着YouTube教程实现了部分功能:助手能播报“All systems nominal”,可以识别语音并重复内容、在终端打印,但语音识别结果始终无法匹配if语句,每次都进入else分支。我怀疑问题出在query = ParseCommand().lower().split()或if query[0] == activationword:这两行。
我的代码如下:
import datetime import speech_recognition as sr import pyttsx3 import webbrowser import wikipedia import wolframalpha #Speech Init engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voices', voices[0].id) #0, male / 1, female activationword = 'Harvey' #should be single word def speak(text, rate = 120): engine.setProperty('rate', rate) engine.say(text) engine.runAndWait() def ParseCommand(): listener = sr.Recognizer() print('Listening for a command') with sr.Microphone() as source: #uses computer default mic listener.pause_threshold = 2 input_speech = listener.listen(source) try: print("Understanding...") query = listener.recognize_google(input_speech, language='en_us') print(f'The input speech was: {query}') except Exception as exception: print("Excuse me?") speak('Excuse me?') print(exception) return 'None' return query # Main Loop if __name__ == '__main__': speak('All systems nominal.') while True: #Parse as a list print("Test 1 Succesful") query = ParseCommand().lower().split() print("Test 2 Succesful") verbal= "I heard", query[0], "is that correct?" speak(verbal) if query[0] == activationword: print("Test 3 Succesful") speak('Listening') query.pop(0) #list commands if query[0] == 'say': if 'hello' in query: speak('Hello Sire, What can I do for you today') else: query.pop(0) #Removes say from the list speech = ''.join(query) speak(speech) else: speak("Sorry sire I'm confused")
问题原因及解决办法
问题核心是大小写不匹配:你把识别到的语音转成了小写(.lower()),但激活词activationword是大写开头的'Harvey',所以query[0]是小写的'harvey',和'Harvey'永远不相等,自然每次都进else分支。
另外还要考虑ParseCommand返回'None'的情况,这时候split()会得到['none'],也会触发else分支,建议额外处理这种情况。
修改方案(二选一即可)
统一激活词为小写:
将activationword = 'Harvey'改成activationword = 'harvey'比较时统一转小写:
将判断条件if query[0] == activationword:改成if query[0] == activationword.lower():
额外优化:处理识别失败的情况
在主循环里,先判断是否是识别失败的返回值,避免后续报错:
while True: print("Test 1 Succesful") query = ParseCommand().lower().split() print("Test 2 Succesful") # 处理识别失败的情况 if query[0] == 'none': continue verbal= "I heard", query[0], "is that correct?" speak(verbal) # 后续判断逻辑...
内容的提问来源于stack exchange,提问作者Griffery64
相关产品推荐
相关产品推荐

