我使用語音識別並檢查一個顏色列表,如果我所說的不在列表中,那麼它會顯示'顏色未找到',如果發現它顯示'顏色發現'我只希望它顯示每條消息一次。 我遇到的問題是如何讓'顏色未找到'味精正確顯示。當語音識別結果不是預期的時候打印消息
# speech recognition
import speech_recognition as speech
#a lot of variables used for loops and conditions
voice = speech.Recognizer()
condition = False
condition2 = False
condition3 = False
boolean = False
counter = 0
counter2 = 0
while condition == False:
#with microphone input as the input
with speech.Microphone() as source:
print("Say something!")
#variable = the input from the microphone
audio = voice.listen(source)
voiceRecog = voice.recognize_google(audio)
try:
#print the word that was heard
print("\nYou said: " + voiceRecog)
except speech.UnknownValueError:
#if couldnt recognise then print this msg
print("Sorry, we couldn't make that out. Try again!")
except speech.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
#list of colours for comparing
colours = ["blue", "red", "Green", "Orange", "yellow", "pink", "purple", "black"]
#loop to check the word spoken against each word in the list
for i in range(len(colours)):
#so that if colour found it doesnt claim colour not found
if boolean == False:
condition2 = False
#increase counters by 1 and change booleans to True
#if spoken word matches any words in the list then output
if colours[i] == voiceRecog:
boolean = True
condition2 = True
condition3 = True
counter += 1
counter2 += 1
print("\nColour Found!\n")
#if user says "quit" then all booleans = True (exit all loops)
elif voiceRecog == "quit":
boolean = True
condition = True
condition2 = True
condition3 = True
#if none of other conditions check value of i and of con2
else:
#if end of list is reached and con2 = False then con3 = False
if (i + 1) == len(colours) and condition2 == False:
condition3 = False
print(end = "")
#if con3 = False then counter increase and print 'colour not found'
if condition3 == False:
print("\nColour not found!\n\n")
counter += 1
#once loop exited by saying quit, print attempts and successful attempts
print("\nYou checked for", counter, "colours and had", counter2, "successful attempts")
以上是我的代碼,下面是一種情況。
說些什麼!
你說:藍色
發現顏色!
說點什麼吧!
你說:綠色
發現顏色!
說點什麼吧!
你說:戴夫戴夫
說點什麼吧!
你說:放棄
您檢查2點的色彩和2次成功嘗試
應該有3次,但2次成功嘗試。
但是,如果我做的其他方式:
說些什麼!
你說:戴夫戴夫
顏色未找到!
說點什麼吧!
你說:史提夫史蒂夫
顏色未找到!
說點什麼吧!
你說:紅色
顏色找到了!
說點什麼吧!
你說:黑
顏色找到!
說點什麼吧!
你說:放棄
您檢查4種顏色,並有2次成功嘗試
我知道它是這樣做的原因,但我不能想出辦法解決它。