Python 如何从该请求中获得所需的值?
我使用rest api模型提出以下请求:Python 如何从该请求中获得所需的值?,python,watson,Python,Watson,我使用rest api模型提出以下请求: def predict(path): with open(path) as img: res = vr.classify(images_file=img, threshold=0, classifier_ids=['food']) print res 当我运行脚本时,我得到: {u'images': [{u'image': u'/tacos.jpg', u'classifiers': [{u'cl
def predict(path):
with open(path) as img:
res = vr.classify(images_file=img, threshold=0, classifier_ids=['food'])
print res
当我运行脚本时,我得到:
{u'images': [{u'image': u'/tacos.jpg', u'classifiers': [{u'classes': [{u'score': 0.0495783, u'class': u'pizza'}, {u'score': 0.553117, u'class': u'tacos'}], u'classifier_id': u'food', u'name': u'food-test'}]}], u'custom_classes': 2, u'images_processed': 1}
但是,我只想得到具有更高值的类,如下所示:
this is the corresponding class: tacos
因此,我想感谢支持修改我的函数以获得所需的输出这是一个字典,因此您可以遍历“类”并找到最高分数 免责声明:我不是python2或watson用户 访问类
res['images'][0]['classifiers'][0]['classes']
所以要遍历这些类
highest_class = ['', 0]
for class in res['images'][0]['classifiers'][0]['classes']:
if class['score'] > highest_class[1]:
highest_class = [class['class'], [class['score']
print "this is the corresponding class: " + highest_class[0]
当然,如果您有1个以上的分类器,那么必须有另一个outside for循环来迭代分类器(如果您需要该功能)使用python本机函数,获得每个分类器id的更高值怎么样?为了清晰起见,使用(太)大的对象名称,并避免代码高尔夫,您可能需要执行以下操作
def predict(path):
with open(path) as img:
res = vr.classify(images_file=img, threshold=0, classifier_ids=['food'])
dict_of_higher_value_per_ = {} # in order to record and reuse values sooner or later.
for image in res['images']:
for classifier in image['classifiers']:
classes = classifier['classes']
classifier_id = classifier['classifier_id']
sorted_scores = sorted(classes,
key=lambda class_:class_['score'],
reverse=True)
best_match = sorted_scores[0] # which corresponds to the best score since elements are sorted.
dict_of_higher_value_per_[classifier_id] = best_match
print "Classifier '{cid}' says this is the corresponding class: {class}".format(cid=classifier_id,
**best_match)
哪张照片
Classifier 'food' says this is the corresponding class: tacos
如果你对我的答案投了反对票,我能解释一下原因吗?非常感谢你的支持,我真的很感激