将.lua表转换为python字典

时间:2016-10-03 18:53:09

标签: python dictionary lua

我有这样的意见:

    sometable = {
        ["a"] = {
            "a1",
        },
        ["b"] = {
            "b1",
            ["b2"] = true,
        },
        ["c"] = {
            "c1",
            ["c2"] = true,
        },
    },

并希望将其转换为我可以在python中使用的字典 - 或者基本上,我只需要能够以这种模式读取数据:

print sometable[b][b2]

最佳解决方案是什么?我试图做一堆替换并使用ast转换它,即:

def make_dict(input): # just body, ie. without 'sometable'
    input = input.replace("=", ":")
    input = input.replace("[\"", "\"")
    input = input.replace("\"]", "\"")
    input = input.replace("\t", "")
    input = input.replace("\n", "")
    input = "{" + input + "}"
    return ast.literal_eval(input)

问题是输出是:

{
 "a" : 
  {"a1", },
 "b" : 
  {"b1", "b2" : true,},
 "c" : 
  {"c1", "c2" : 1,},
}

错误(invalid syntax)位于{"b1", "b2" : true,},。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

请看这个包:https://github.com/SirAnthony/slpp

>>> from slpp import slpp as lua
>>> code = """{
    ["a"] = {
        "a1",
    },
    ["b"] = {
        "b1",
        ["b2"] = true,
    },
    ["c"] = {
        "c1",
        ["c2"] = true,
    },
}"""
>>> print(lua.decode(code))
{'a': ['a1'], 'c': {0: 'c1', 'c2': True}, 'b': {0: 'b1', 'b2': True}}