如果条件不能在python中比较浮点数

时间:2017-09-08 06:48:00

标签: python django if-statement

如果我的代码中的条件无法正常工作。 这是我的代码:

if request.method == 'POST':
    ask =request.POST['ask']
    model_directory ="dialog/rasa/models/model_20170831-105056"

    metadata = Metadata.load(model_directory)   # where model_directory points to the folder the model is persisted in
    interpreter = Interpreter.load(metadata, RasaNLUConfig("dialog/rasa/config_mitie_sklearn.json"))
    r=interpreter.parse(ask)
    # r = requests.get('http://localhost:5000/parse', params={'q':ask})
    # r = r.json()

    intent = r['intent']['name']
    text = r['text']
    confidence = r['intent']['confidence']
    confidence = float(confidence)
    confidence = round(confidence,2)
    #confidence =type(confidence)


    if r['entities']:
        entity =r['entities'][0]['entity']
        value =r['entities'][0]['value']
        query=Dialog.objects.raw('SELECT 1 id,dialog FROM test WHERE intent=%s AND entity=%s AND value=%s', [intent,entity,value])
    else:
        query=Dialog.objects.raw('SELECT 1 id,dialog FROM test WHERE intent=%s', [intent])

    for x in query:
        dialog = ""

        if confidence < 0.50:
            dialog = "Sorry"
            # result = {"conversation": {"text":text,"intent": intent,"confidence":confidence,"entity":entity,"value":value,"output": dialog,"context": "null"}}
            # result = json.dumps(result,sort_keys=True, indent=4)
        else:
            dialog = "ok"
            #dialog=unidecode.unidecode(x.dialog)
            # result = {"conversation": {"text":text,"intent": intent,"confidence":confidence,"entity":entity,"value":value,"output": dialog,"context": "null"}}
            # result = json.dumps(result,sort_keys=True, indent=4)

    return HttpResponse(dialog)

只有其他部分正在运作。当置信度小于0.50

"local variable 'dialog' referenced before assignment error" 

来。置信度类型为numpy.float64。我使用的是python 2.7。

3 个答案:

答案 0 :(得分:1)

如果query为null,则不定义对话框。

固定为自爆

dialog = "ok"
for x in query:
    if confidence < 0.50:
        dialog = "Sorry"

答案 1 :(得分:-1)

这是一种正常的Python行为。在if阻止之前未定义对话框。即使您有else语句,Python仍然认为它可能会显示未在任何地方定义的内容。例如,如果您的if条件无法评估为True或False,该怎么办?

在if块之前的某处定义对话框,一切都应该没问题,不要改变你要做的事情!

答案 2 :(得分:-3)

我只能使用空查询重现您的错误:

import numpy as np
confidence = np.float64(0.2)
confidence = float(confidence)
confidence = round(confidence, 2)

query = []
for x in query:
    print x
    if confidence < 0.50:
        dialog = "Sorry"
    else:
        dialog = "ok"

print dialog

你可以尝试

if not query:
    dialog = "Sorry Epmty query"
for x in query:
    if confidence < 0.50:
        dialog = "Sorry"
    else:
        dialog = "ok"