【发布时间】:2021-10-31 20:14:53
【问题描述】:
我有一个 JSON 数据,下面是部分数据的图片
通过这些数据,我想提取“文本”和“索引”值,它们是可以在“实体”键中找到的子键。我尝试使用以下方法进行此操作
with open('tweets.json') as f:
data = json.load(f)
for item in data:
for key, value in item['entities'].items():
for v in value:
if value:
s_index = (v['indices'][0])
e_index = (v['indices'][1])
all_texts = (v['text'])
我设法检索“索引”值以将它们存储到各自的属性中。但是我在接收“文本”值时遇到问题,因为他们说有一个关键错误,如下所示
KeyError Traceback (most recent call last)
<ipython-input-4-5729d0d2fa15> in <module>
12 s_index = (v['indices'][0])
13 e_index = (v['indices'][1])
---> 14 all_texts = (v['text'])
15
16 #cur.execute('INSERT INTO entities (tweet_id, type, value, start_index, end_index) VALUES (?, ?, ?, ?, ?)',
KeyError: 'text'
【问题讨论】:
标签: python json dictionary for-loop