将.lua表格转换为python字典

我有这样的输入:

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

我想要将它转换成一个可以在python中处理的字典 - 或者说,我只需要能够以这种方式读取数据:

print sometable[b][b2]

最佳解决方案是什么?我试图通过一堆替换和使用 ast 来进行转换,例如:

def make_dict(input): # 只是body,即没有 '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,},。有什么建议吗?

点赞
用户847552
用户847552

看一下这个包: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}}
2016-10-03 19:06:45