在Python中显示特定于JSON的JSON结果

2024-10-03 04:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,有以下代码:

def doSentimentAnalysisAndPrint(keyval):  
    import urllib

    data = urllib.urlencode(keyval) 
    u = urllib.urlopen("http://text-processing.com/api/sentiment/", data)
    json_string = u.read()   

    parsed_json = json.loads(json_string)

    # print the various key:values
    print(parsed_json['probability'])
    print ">>", parsed_json['label']

打印结果为:

{u'neg': 0.24087437946650492, u'neutral': 0.19184084028194423, u'pos': 0.7591256205334951}
>> pos

我只想打印出实际结果?例如,在这种情况下,“肯定:0.7591256205334951”,但不知道如何实现这一点


Tags: 代码posimportjsondatastringdefurllib
1条回答
网友
1楼 · 发布于 2024-10-03 04:31:59

使用时请务必阅读API documentation'label'键指向'probability'字典中的关键是确定的情绪:

label: will be either pos if the text is determined to be positive, neg if the text is negative, or neutral if the text is neither pos nor neg.

probability: an object that contains the probability for each label. neg and pos will add up to 1, while neutral is standalone. If neutral is greater than 0.5 then the label will be neutral. Otherwise, the label will be pos or neg, whichever has the greater probability.

所以您已经有了一个标签,相应的值只是一个键查找。将标签值映射到要打印的字符串(如pos映射到Positive),并将两者结合起来:

sentiments = {'pos': 'Positive', 'neg': 'Negative', 'neutral': 'Neutral'}
label = parsed_json['label']
print sentiments[label], parsed_json['probability'][label]

相关问题 更多 >