您好我正在使用如下所示的json文件:
{
"workspace_id": "car-dashboard-en",
"name": "Car Dashboard - Sample",
"created": "2017-03-20T21:24:41.498Z",
"intents": [
{
"intent": "about_VA",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z",
"examples": [
{
"text": "any music reccomendation?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "can you recommend ood jazz music?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "cloud you recommend music?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "your name",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
}
],
"description": null
},
{
"intent": "capabilities",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z",
"examples": [
{
"text": "adapt to current weather condition",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "book a flight for NY on sunday",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "can you change lanes",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
我有一个json有一个名为' intents'这部分由几个意图组成,每个意图都有一个名为' text',
的值列表我想从这个文件中提取一个字典,如下所示:
dictionary = {'intent_name':[text1,text1,text3,...],'intent_name2':[text1,text2,text3,...],...}
此词典的关键是相关意图的名称,值是此意图的每个文本,
不幸的是我是一个使用json文件的初学者,所以我尝试了:
import json
with open('workspace-car-dashboard-en.json') as json_file:
data = json.load(json_file)
使用以下代码我将提取并打印所有文本值,如下所示:
for element in data['intents']:
for element2 in element['examples']:
print(element2['text'])
我得到了:
any music reccomendation?
can you recommend ood jazz music?
cloud you recommend music?
do you hate
Do you like
do you love
但是我无法动态构建字典并附加所有文本值,所以我真的很感谢支持来完成这项艰巨的任务。 我无法包含完整的json文件,因为它非常大,所以我希望这个例子足够了。
答案 0 :(得分:1)
创建一个新的空字典。添加每个意图名称的键并设置空列表的值。 然后使用您创建的示例文本从循环中插入每个文本键值。
import json
with open('workspace-car-dashboard-en.json') as json_file:
data = json.load(json_file)
new_dic = {}
for element in data['intents']:
new_dic[element['intent']] = []
for element2 in element['examples']:
new_dic[element['intent']] += [element2['text']]