0

我正在尝试将此文本文件转换为 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

感谢您的帮助。

4

2 回答 2

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
于 2013-03-03T05:05:13.240 回答
2

将数据转换为 json,然后将 json 读入变量。

测试.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)
于 2013-03-03T07:35:26.160 回答