将.lua表转换为python字典 [英] Converting .lua table to a python dictionary

查看:1011
本文介绍了将.lua表转换为python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种输入:

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

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

And would like to convert it to some dictionary I can work with in python - or basically, I just need to be able to read the data in this pattern:

print sometable[b][b2]

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

What is the best solution to this? I tried to do a bunch of replaces and convert it using ast, ie:

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,},上.有什么建议吗?

The error (invalid syntax) is on {"b1", "b2" : true,},. Any suggestion?

推荐答案

查看此软件包: 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}}

这篇关于将.lua表转换为python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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