如何将通过Web调用接收的文本文件转换为字典?

时间:2013-03-03 04:15:39

标签: python dictionary

我正在尝试将此text文件转换为python字典。

基本格式是

"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

感谢您的帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)