2017-12-04 16 views
0

こんにちは、私は次のように見えるJSONファイルで働いています: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を持っています私は次のようにこのファイルから辞書を抽出したい「テキスト」、

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ファイルを含めることができませんでしたので、この例で十分です。

答えて

1

新しい空のdictを作成します。各インテント名のキーを追加し、空のリストの値を設定します。 次に、作成したサンプルテキストを使用して、ループから各テキストキー値を挿入します。

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']] 
+0

これは非常に便利でした – neo33

関連する問題