2015-11-07 33 views
0

我描述/標題可能缺乏,因爲我新的Python,但是作爲一個例子,我現在有數據像下面存儲在變量bunnies展開詞典列表爲可讀格式

'{''''''''''''''''''''',''''','''''''','''''','''','''''','廚師','etc':'etc','etc': 'etc'},{'rabbithole':{'holenumber':2,'family':'roger','status': 'elite'} ,'食物':'牛排','兒童':108,'工作':'廚師','等':'etc', 'etc':'etc'},{'rabbithole':{'holenumber' :3,'家庭':'羅傑', 'status':'elite'},'food':'steak','children':108,'job':'chef', 'etc':'etc','etc':'etc'}]

我的目標是把它分解成一個可讀的格式如下:

{ 
'rabbithole': { 
    'holenumber': 1, 
    'family': 'roger', 
    'status': 'elite' 
}, 
'food': 'steak', 
'children': 108, 
'job': 'chef', 
'etc': 'etc', 
'etc': 'etc' 
} 

... 

我到目前爲止是這樣的......

def virt(list): 
    for i in list: 
     print i 
     print "\n" 

virt(bunnies) 

,給了我一個新的生產線爲每rabbithole上市...

所以我想這:

import re 
def virt(list) 
    for i in list: 
     match = re.search(r'{|.*: {.*},|.*:.*,|}',i, re.I) 
     print i.replace(match,match+"\n") 

virt(bunnies) 

不幸的是這並沒有這樣做,除了從重新庫拋出錯誤東西。

File "/usr/lib64/python2.7/re.py", line 146, in search 
    return _compile(pattern, flags).search(string) 

我還沒有看到太多的錯誤,但我有一種感覺,我反正走錯了方向。

任何人都可以幫助指向正確的方向嗎?

+0

您應該查看'pprint'模塊,如果你只是看漂亮的印刷 – ozy

+0

我帶進去一看這太,謝謝ozy – Procyclinsur

+0

json模塊更好地分解了{},但這個更簡單一點。 – Procyclinsur

回答

1

可以使用json Python模塊:

import json 

print json.dumps(your_data, sort_keys=True, indent=4, separators=(',', ': ')) 

例子:

a=json.dumps([{'rabbithole': {'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 2, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 3, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}], sort_keys=True, indent=4, separators=(',', ': ')) 
>>> print a 
[ 
    { 
     "children": 108, 
     "etc": "etc", 
     "food": "steak", 
     "job": "chef", 
     "rabbithole": { 
      "family": "roger", 
      "holenumber": 1, 
      "status": "elite" 
     } 
    }, 
    { 
     "children": 108, 
     "etc": "etc", 
     "food": "steak", 
     "job": "chef", 
     "rabbithole": { 
      "family": "roger", 
      "holenumber": 2, 
      "status": "elite" 
     } 
    }, 
    { 
     "children": 108, 
     "etc": "etc", 
     "food": "steak", 
     "job": "chef", 
     "rabbithole": { 
      "family": "roger", 
      "holenumber": 3, 
      "status": "elite" 
     } 
    } 
] 
+0

我現在試試這個,讓你知道它是如何工作的。 – Procyclinsur

+0

スゲー或英文,神聖的牛...簡單,重點...我需要更多地瞭解json庫... – Procyclinsur