为什么我的代码要求定义一个无法定义的变量?

时间:2018-08-30 04:15:30

标签: python nameerror

因此,我有一段代码是对神经网络进行分类的文本。我正在尝试对其进行修改,以便可以对用户的输入进行分类。这是原始的:

def SpeechToTextAndClassification(sentence, show_details=False):
results = think(sentence, show_details)

results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ] 
results.sort(key=lambda x: x[1], reverse=True) 
return_results =[[classes[r[0]],r[1]] for r in results]
print ("%s \n classification: %s" % (sentence, return_results))
return return_results

SpeechToTextAndClassification("yes")

这是修改后的版本:

def SpeechToTextAndClassification(command, sentence, show_details=False):

results = think(sentence, show_details)

results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ] 
results.sort(key=lambda x: x[1], reverse=True) 
return_results =[[classes[r[0]],r[1]] for r in results]
print ("%s \n classification: %s" % (sentence, return_results))
return return_results

print ()
print("run check")
talkToMe("I am ready, sir") #text to speech
command = myCommand()
print(command)
SpeechToTextAndClassification(command, sentence, show_details=True)

问题是它给句子带来了错误-句子是训练数据的一部分,如下所示:

training_data = []
training_data.append({"class":"yes", "sentence":"Yes "})
training_data.append({"class":"yes", "sentence":"Yeah"})
training_data.append({"class":"yes", "sentence":"Yup "})
training_data.append({"class":"yes", "sentence":"Yes it does"})

出现以下错误:

line 319, in <module>
SpeechToTextAndClassification(command, sentence, show_details=True)
NameError: name 'sentence' is not defined

我将如何更改它以便它可以使用用户的输入呢?谢谢!

1 个答案:

答案 0 :(得分:0)

对不起!我能够修复自己的代码。我将命令(语音到文本)更改为句子,然后像这样重新声明:

def SpeechAndTextClassification(sentence, show_details=False):
    results = think(sentence, show_details)

    results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ] 
    results.sort(key=lambda x: x[1], reverse=True) 
    return_results =[[classes[r[0]],r[1]] for r in results]
    print ("%s \n classification: %s" % (sentence, return_results))
    return return_results

sentence = myCommand()
sentence #executing the function 
talkToMe("hello world")
SpeechAndTextClassification(sentence)

现在就像魅力一样!