2017-02-23 52 views
-4

作爲新的Python我試圖找出如何在下面的格式樣本文件可能被分成多個部分,基於與鍵「類型」關聯的值將其存儲在一個單獨的字典。可對任何人分享一些投入這個。謝謝。如何基於密鑰分離大文件並使用python將文件存儲在單獨的字典中?

[ 
{"type": "A", "verb": "NEW", "key": "96f55c7d8f42", "event_time": "2017-01-06:12:46:46.384Z", "last_name": "Smith", "adr_city": "Middletown", "adr_state": "AK"}, 
{"type": "B", "verb": "NEW", "key": "ac05e815502f", "event_time": "2017-01-06:12:45:52.041Z", "customer_id": "96f55c7d8f42", "tags": {"some key": "some value"}}, 
{"type": "C", "verb": "UPLOAD", "key": "d8ede43b1d9f", "event_time": "2017-01-06:12:47:12.344Z", "customer_id": "96f55c7d8f42", "camera_make": "Canon", "camera_model": "EOS 80D"}, 
{"type": "D", "verb": "NEW", "key": "68d84e5d1a43", "event_time": "2017-01-06:12:55:55.555Z", "customer_id": "96f55c7d8f42", "total_amount": "12.34 USD"} 
] 
~  

回答

0

假設你的文件是data.txt,試試這個:

import json 

with open('data.txt') as data_file: 
    data = json.load(data_file) 

for row in data: 
    print("Type: " + row['type']) 
    print(row) 
    print() 
+0

我想將數據存儲在單獨的數據結構中,並將其用於我將應用於這些數據結構的以下函數中。 – Teja

+0

那麼你可以顯示下面的代碼嗎?編輯原始帖子。 –

+0

我仍然需要編寫它,但是我面臨的問題是根據類型屬性將數據存儲到單獨的字典中。 – Teja

0

最簡單的方法是可能與詞典的詞典。

編寫一個讀取每行的迭代器,並使用ujson將文本解析爲dict。然後pop你想用作鍵的值,並返回兩個部分。

import ujson 

def read_lines(file_path): 
    with open(file_path, 'r') as fh: 
     for line in fh: 
      dictionary = ujson.loads(line) 
      key = dictionary.pop('key') 
      yield key, dictionary 


dictionaries = dict() 
for key, value in read_lines(r"/foo/bar/file.txt"): 
    dictionaries[key] = value 
相關問題