[英]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)
通過sed -i 's/\\'/\\"/g' sample.json
將單引號更改為雙引號
轉換為 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.