我想在python中将txt变成dict

时间:2018-02-05 17:29:55

标签: python dictionary

所以我有以下数据:

Apples = 1
Bananas = 1
Box_Cashew = 
{ 
    Cashew = 1
}
Dragonsfruit = 2
Crate_box_epox=
{
    box_epox = 
        {
             epox = 2
        }
}

并希望从这个txt创建一个Dictionary,如下所示:

{'Apple':'1' , 'Bananas' : '1' , 'Box_Cashew' : {'Cashew':'1'} , 'Dragonsfruit' : '2', 'Crate_box_epox' : { 'box_epox' : {'epox':2}}}

我尝试逐行阅读下面的代码,但是当我在一个字典中得到一个字典时,我不知道该怎么做。

编辑:

@PrestonM和@ juanpa.arrivillaga

文本文件:

unit=9023
state=1411
flags=
{
    1NobelChemistry=yes
    1NobelLiterature=yes
    1NobelMedicine=yes
}
worldmarket=
{
    worldmarket_pool=
    {
        ammunition=204.50766
    }
}

代码:

text_file = open("teste.v2", "r")
lines = text_file.readlines()
d={}
for line in lines:
        try:
            (key1, val) = line.replace('\t','').replace('\n','').split('=')

            d[str(key1)] = val
        except:
            pass       

结果:

>>>d
{'unit':'9023' , 'state':'1411' , 'flags':{},'1NobelChemistry':'yes' , '1NobelLiterature':'yes' , '1NobelMedicine':'yes','worldmarket':{},'worldmarket_pool':{},'ammunition':'204.50766'}

期望的结果:

>>>d
{'unit':'9023' , 'state':'1411' , 'flags':{ '1NobelChemistry':'yes' , '1NobelLiterature':'yes' , '1NobelMedicine':'yes'},'worldmarket':{'worldmarket_pool':{'ammunition':'204.50766'}}}

3 个答案:

答案 0 :(得分:1)

以下似乎适用于我的测试。我希望例外中的评论和文字能够清楚说明正在做什么。

在您的代码中,您只需将所有内容添加到同一个词典中,这不会产生您之后的结果。遇到{时,您希望开始将键/值对添加到新字典中,该字典实际存储在旧字典中。为此,下面的代码会在列表中跟踪这些词典,必要时添加一个词典,并从列表中删除一个词典以返回上一个词典。

dictStack = [ { } ]
currentKey = None
for l in lines:
    l = l.strip() # Remove whitespace at start/end
    if not l: # skip empty line
        continue

    if l == "{":
        if currentKey is None:
            raise Exception("Current key not set!")

        newDict = { }
        dictStack[0][currentKey] = newDict
        dictStack.insert(0, newDict)
        currentKey = None
    elif l == "}":
        if currentKey is not None:
            raise Exception("Current key is set, expecting {")

        if len(dictStack) == 1:
            raise Exception("Can't remove the final dict, there seems to be an extra '}'")
        dictStack.pop(0)
    else:
        if currentKey is not None:
            raise Exception("Current key is set, expecting {")

        if not "=" in l:
            raise Exception("Expecting '=' in '{}'".format(l))

        key, value = l.split("=")
        key, value = key.strip(), value.strip() # remove whitespace
        if not value:
            currentKey = key
        else:
            dictStack[0][key] = value


if len(dictStack) != 1:
    raise Exception("Still more than one dict in the stack")

result = dictStack[0]

答案 1 :(得分:1)

这是我使用递归的解决方案:

import re

def text2dict(text):
    def f(ls, i):
        d = {}

        while i < len(ls):
            if ls[i]=="}":
                return d, i

            m = re.match(r"(.*)=(.*)", ls[i])
            k = m.group(1).strip()
            v = m.group(2).strip()

            if not len(v):
                v, i = f(ls, i+2)
            d[k] = v
            i += 1
        return d
    return f([l.strip() for l in text.split("\n")], 0)

with open("file.txt") as f:
    text = f.read()
print(text2dict(text))

答案 2 :(得分:0)

"Unresolved External Symbol Base<0>::i ...."

结果:

def make_dict(text):
    l = "{"
    t = text.splitlines()
    for j,i in enumerate(t):
        if i != '':
            line = i.replace(" ", "").split('=')
            next = t[j + 1].replace(" ", "").split('=')[0] if len(t) > (j + 1) else "}"
            if line[0] == "{" or line[0] == "}":
                l += line[0]
            else:   
                l += ("'"+line[0] + "':" + ("'"  + line[1] + "'" + ("," if next != "}" else "") + "" if line[1] != '' else ""))
    l += "}"            
    print(l)            

make_dict(text)
相关问题