簡體   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