繁体   English   中英

python - 在 json 上获取特定值

[英]python - get specific value on json

我想在这个 json 中获得 'Lemma' 的每个值:

{'sentences': 
   [{'indexeddependencies': [], 'words': 
     [
        ['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}], 
        ['.', {'CharacterOffsetBegin': '14', 'CharacterOffsetEnd': '15', 'Lemma': '.', 'PartOfSpeech': '.', 'NamedEntityTag': 'O'}]
     ], 'parsetree': [], 'text': 'Cinnamomum.', 'dependencies': []
    }, 
    {'indexeddependencies': [], 'words': 
      [
        ['specific', {'CharacterOffsetBegin': '16', 'CharacterOffsetEnd': '24', 'Lemma': 'specific', 'PartOfSpeech': 'JJ', 'NamedEntityTag': 'O'}],
        ['immunoglobulin', {'CharacterOffsetBegin': '25', 'CharacterOffsetEnd': '39', 'Lemma': 'immunoglobulin', 'PartOfSpeech': 'NN', 'NamedEntityTag': 'O'}],
        ['measurement', {'CharacterOffsetBegin': '51', 'CharacterOffsetEnd': '62', 'Lemma': 'measurement', 'PartOfSpeech': 'NN', 'NamedEntityTag': 'O'}]
      ], 'parsetree': [], 'text': 'specific immunoglobulin measurement', 'dependencies': []
     }]
}

如何使用 python 获取每个值? 有五个引理键,但我无法全部获取。

我试过这个,但它不起作用:

for i in range(len(words)): #in this case the range of i would be 5
      lemma = result["sentences"][0]["words"][i][1]["Lemma"]

我不确定为什么你有这个数据结构 - 假设你不能改变/重塑它以更好地适应你的查询和用例,并且Lemma键总是存在:

>>> [word[1]['Lemma'] 
     for sentence in data['sentences'] 
     for word in sentence['words']]
['Cinnamomum', '.', 'specific', 'immunoglobulin', 'measurement']

这个简单的代码遍历所有内容并找到所有引理值(顺便说一句。你的 json 应该有 " 而不是 ' 作为字符串引号,我猜:

import json

with open('lemma.json') as f:
    data = json.load(f)


def traverse(node):
    for key in node:
        if isinstance(node, list):
            traverse(key)
        elif isinstance(node, dict):
            if key == 'Lemma':
                print key, node[key]
                continue
            traverse(node[key])

traverse(data)

您可以使用JSON 编码器和解码器库

如果你使用那个库,你会写:

import json json.loads(result)

无论如何,我尝试将您的 json 放入验证器中,但出现错误

  1. 通过sed -i 's/\\'/\\"/g' sample.json将单引号更改为双引号

  2. 转换为 json 对象并通过模块json import json with open('sample.json', encoding='utf-8') as data_file: data = json.loads(data_file.read()) for sentence in data['sentences']: for word in sentence['words']: print(word[1]['Lemma'])

结果: Cinnamomum . specific immunoglobulin measurement Cinnamomum . specific immunoglobulin measurement

暂无
暂无

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

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