繁体   English   中英

如何从我作为来自 Monkeylearn 的 API 响应的 python 子列表中仅提取特定值

[英]How to extract only a specific value from a python sublist that I got as an API response from Monkeylearn

我一直在 Monkeylearn 中训练文本分类 model,作为对我的 API 查询的响应,我得到了一个 python 列表。 我只想从中提取特定的文本分类值。 附上下面的代码。

ml = MonkeyLearn('42b2344587')
data = reddittext[2]    # dataset in a python list
model_id = 'cl7C'
result = ml.classifiers.classify(model_id, data)
print(result.body)   #response from API in list format

Output 我得到的是:

[{'text': 'comment\n', 'external_id': None, 'error': False, 'classifications': []},
 {'text': 'So this is the worst series of Kohli like in years.\n', 'external_id': None, 'error': False, 'classifications': []}, 
 {'text': 'Saini ODI average at 53 😂\n', 'external_id': None, 'error': False, 'classifications': [{'tag_name': 'Batting', 'tag_id': 122983950, 'confidence': 0.64}]}]

我只想从这个列表中打印分类 - tag_name 即“击球”。

type(result.body)

我得到的 output 是:列表

result.body是字典和文本的列表,也称为 JSON 格式。

您可以通过使用 for 循环遍历列表并使用d["key"]执行字典查找(如果您知道该键存在)或d.get("key")如果您不知道是否键存在于字典中。 如果 key tag_name不存在, get命令将返回None

for entry in result.body:
    for classification in entry['classifications']:
        tag_name = classification.get('tag_name')
        if tag_name is not None:
            print(tag_name)

由于我不知道响应格式是否固定,假设它不是。

使用 Json 对字符串的响应进行编码,并使用正则表达式查找字符串。

这样,您可以匹配多次出现。 由于您最有可能收到 json 文件,因此 json 模块不会抱怨对其进行编码。

import json
import re


testcase = [{'text': 'comment\n', 'external_id': None, 'error': False, 'classifications': []},
            {'text': 'So this is the worst series of Kohli like in years.\n', 'external_id': None, 'error': False, 'classifications': []},
            {'text': 'Saini ODI average at 53 😂\n', 'external_id': None, 'error': False, 'classifications': [{'tag_name': 'Batting', 'tag_id': 122983950, 'confidence': 0.64}]}]


# if data format is fixed
print(testcase[-1]['classifications'][0]['tag_name'])


# if not, expensive but works.
def json_find(source, key_name):
    json_str = json.dumps(source)
    pattern = f'(?<={key_name}": ")([^,"]*)'
    found = re.findall(pattern, json_str)
    return found

print(json_find(testcase, 'tag_name')[0])

结果:

击球
击球

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM