字符串比较未给出与已识别语音数据的预期结果

String comparison doesn't give the intended result with recognized speech data

好的,所以我有了这个代码来 运行 语音识别并收集话语。然后想用一个已经保存在数据库中的单词来检查。

def recog():
    r = sr.Recognizer()
    print("Speak Now:")
    with sr.Microphone() as source:
        audio_data = r.listen(source)
        try:
            print("recognizing")
            recog.result = str(r.recognize_wit(audio_data, key="XDAYDVOGVTRP652K6TAWOWQR73WHJY6S"))
            print(recog.result)
            return recog.result
        except sr.UnknownValueError:
            print('Recognition error')

我使用下面的这段代码来检索需要与之比较的词。

conn = sqlite3.connect('VIT.db')
c = conn.cursor()
post_ac = "select ans from ansc where id=" + str(i)
c.execute(post_ac)
conn.commit()
records = c.fetchone()
print(records)
print_c = ''+str(records)
conn.close()

然后我使用 if 语句来检查它们是否匹配

if print_c == recog():
    print("Correct")
else:
    print("Incorrect")

但是这段代码总是给我“正确”的答案。我做错了什么以及如何改进我的代码?我对 python 和 tkinter 还很陌生,所以请原谅我的错误。 p.s:仅供参考,从数据库和识别中成功并正确地检索了数据。我在比较方面遇到了麻烦。

你的print语句是倒过来的,所以它实际上一直在告诉你'incorrect'一切。您也只是粗略地比较了 2.

# '==' instead of 'in'
if print_c == recog(): # consider 'home' is IN 'homestead', but they aren't the same
    print("Incorrect") # shouldn't this be 'Correct'
else:
    print("Correct")   # ..and this 'Incorrect'?

None 你的问题与 tkinter 有关。您可以删除该标签。

过了一会儿,我有点弄明白出了什么问题,我已经更改了代码。一直在比较

'string'

而不是

string

conn = sqlite3.connect('VIT.db')
c = conn.cursor()    
post_ac = "select ans from ansc where id=" + str(i)
c.execute(post_ac)
records = c.fetchone()
print_c = str(records[0])
print(print_c)

所以我所要做的就是将 print_c = ''+str(records) 更改为 print_c = str(records[0]) ,这样它就会在 if 语句中正确比较。感谢任何人试图回答并希望这对任何需要的人有所帮助。