gpt4 book ai didi

python - 属性错误: Dict has no object class_name

转载 作者:太空宇宙 更新时间:2023-11-03 15:16:37 24 4
gpt4 key购买 nike

我正在尝试解析一个网站,对其进行标记并将不同的句子存储在一个数组中,因此这变成了一个字符串数组。我需要访问从 json 返回的类。例如,我必须上课:nhate和hate。如果该类别令人讨厌并且该类别的置信度 > 0.50,则执行某些操作。但是我无法访问这些类(class)。

words = text.split(".")
c=0
for i in words:

if not words[c]:
words[c] = "this was empty before."
classes = natural_language_classifier.classify('90e7b4x199-nlc-36073',words[c])
result = json.dumps(classes, indent=2)
if (classes.class_name == 'hate' and classes.confidence > 0.50):
print(json.dumps(classes, indent=2))
c=c+1

我得到的错误是:

Traceback (most recent call last):                        
File "parse.py", line 45, in <module>
if (classes.class_name == 'hate' and classes.confidence > 0.50)
AttributeError: 'dict' object has no attribute 'class_name'

编辑:我得到的json是这样的:

{
"classifier_id": "10D41B-nlc-1",
"url": "https://gateway.watsonplatform.net/natural-language-classifier /api/v1/classifiers/10D41B-nlc-1/classify?text=How%20hot%20wil/10D41B-nlc-1",
"text": "How hot will it be today?",
"top_class": "nhate",
"classes": [
{
"class_name": "nhate",
"confidence": 0.9998201258549781
},
{
"class_name": "hate",
"confidence": 0.00017987414502176904
}
]
}

已编辑

打印(类)给我:

    {u'url': u'https://gateway.watsonplatform.net/natural-language-classifier/api/v1
/classifiers/90e7b4x199-nlc-36073',
u'text': u' A Partnership With Abu Shaklak Printing House',
u'classes':
[{u'class_name': u'nhate.', u'confidence': 0.9398546
187612434}, {u'class_name': u'hate.', u'confidence': 0.0449277873541271}, {u'cla
ss_name': u'Feels good man', u'confidence': 0.015217593884629425}], u'classifier
_id': u'90e7b4x199-nlc-36073', u'top_class': u'nhate.'}

最佳答案

你也许可以做这样的事情:

import json

# For demonstration purposes, use the data from the question rather than calling the api:

# data = natural_language_classifier.classify('90e7b4x199-nlc-36073',words[c])

data = json.loads("""{
"classifier_id": "10D41B-nlc-1",
"url": "https://gateway.watsonplatform.net/natural-language-classifier /api/v1/classifiers/10D41B-nlc-1/classify?text=How%20hot%20wil/10D41B-nlc-1",
"text": "How hot will it be today?",
"top_class": "nhate",
"classes": [
{
"class_name": "nhate",
"confidence": 0.9998201258549781
},
{
"class_name": "hate",
"confidence": 0.00017987414502176904
}
]
}""")

def hate_gt(data, confidence):
if 'classes' in data:
for cls in data['classes']:
if cls['class_name'] == 'hate' and cls['confidence'] > confidence:
return True
return False

print(hate_gt(data, 0.00001)) # True
print(hate_gt(data, 0.5)) # False

在这里试试:https://repl.it/Hl9b/1

我不确定这个 API 合约是什么样的,所以我不想做出任何假设“讨厌”将始终是数组中的第二项。

另请注意,我将 classes 变量名称更改为 data,因为 classes['classes'] 令人困惑。

关于python - 属性错误: Dict has no object class_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com