如何将通过网络电话接收的文本文件转换为字典? [英] How do I convert a text file received via a web call to a dictionary?

查看:125
本文介绍了如何将通过网络电话接收的文本文件转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换此文本文件到一个python字典。

I am attempting to convert this text file to a python dictionary.

基本格式是

"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"
        }
    }
}

这个文件几乎是一个字典,但不完整。有没有办法将其转换成字典,以便我可以通过键访问字典的每个级别?我想做一些类似的东西:

This file is almost a dictionary, but not quite. Is there a way to convert this into a dictionary so that I can access each level of the dictionary by the keys? I'd like to do something like:

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

感谢您的帮助。

推荐答案

这是丑的,但似乎工作,假设链接的文件是 test.txt

This is ugly, but it seems to work, assuming the linked file is 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

这篇关于如何将通过网络电话接收的文本文件转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆