2013-03-03 66 views
0

我試圖將text文件轉換爲python字典。如何將通過Web調用接收的文本文件轉換爲字典?

的基本格式是

"items_game" 
{ 
    "game_info" 
    { 
     "first_valid_class"   "1" 
     "last_valid_class"   "9" 
     "first_valid_item_slot"  "0" 
     "last_valid_item_slot"  "10" 
     "num_item_presets"   "4" 
    } 
    "qualities" 
    { 
     "key"   "value" 
    } 
    ... 
    "community_market_item_remaps" 
    { 
     "Supply Crate" 
     { 
      "Supply Crate 2"   "1" 
      "Supply Crate 3"   "1" 
     } 
     "Decoder Ring" 
     { 
      "Winter Key"    "1" 
      "Summer Key"    "1" 
      "Naughty Winter Key 2011" "1" 
      "Nice Winter Key 2011"  "1" 
      "Scorched Key"    "1" 
      "Fall Key 2012"    "1" 
      "Eerie Key"     "1" 
      "Naughty Winter Key 2012" "1" 
      "Nice Winter Key 2012"  "1" 
     } 
    } 
} 

該文件幾乎是一本字典,但並不完全。有沒有辦法將它轉換成字典,以便我可以通過鍵訪問字典的每個級別?我想要這樣做:

foreach key in dictName['items_game']['community_market_item_remaps']['Decoder Ring']: 
    # do something 

謝謝你的幫助。

回答

4

這是醜陋的,但它似乎工作,假設鏈接文件是test.txt

import re 

a = open('test.txt').read() 

a = a.replace('\n', '').replace('\t', ' ') 
a = a.replace('{', ':{').replace('}', '},\n') 

b = re.sub('(\".*?\") *(\".*?\")', r'\1:\2,', a) 

b = "{%s}" % b 

dictName = eval(b) 
for key in dictName['items_game']['community_market_item_remaps']['Decoder Ring']: 
    print key 

輸出是:

Fall Key 2012 
Eerie Key 
Nice Winter Key 2011 
Nice Winter Key 2012 
Summer Key 
Scorched Key 
Winter Key 
Naughty Winter Key 2011 
Naughty Winter Key 2012 
2

將數據轉換成JSON,然後讀取JSON成變量。

test.txt

import re 
import json 
a = open('test.txt').read() 
a = re.sub('"[ \t]*"', '":"', a) 
a = re.sub('"\s+"', '","', a) 
a = re.sub('"\s+{', '":{', a) 
a = re.sub('}\s+"', '},"', a) 
a = '{%s}' % a 
b = json.loads(a) 
+0

使用json.loads()避免來自外部源的數據上運行的eval()。我喜歡這種方法。 – Neil 2013-03-04 01:56:03