将.lua表格转换为Python字典

3

我有这样一种输入:

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

错误(无效语法)在{"b1", "b2" : true,},上。有什么建议吗?

你需要将"b1"转换为"b1":None或类似的内容 - 字典中不能有没有值的键。顺便说一下,{"a1", }不是字典,而是set() - 尝试print(type({"a1", })),你会得到<class 'set'> - furas
如何将"b1"转换为"b1":None,已知上面提到的函数?我猜需要使用一些模式匹配来找到"something,",然后将其替换为"something:None,",但是我不确定如何做到这一点。 - emihir0
只是好奇,你为什么想要在Python中使用它? :) - warspyking
我觉得这里不需要使用Python中介,但我也不知道具体情况,所以我可能完全错了。 - warspyking
为什么你不能在Lua端进行计算?@emihir0 - warspyking
显示剩余2条评论
1个回答

5

看看这个包: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}}

我在安装时遇到了问题。例如,pip install slpp 告诉我没有这样的包,在他们的github上我也找不到任何“安装”指南。有什么建议吗? - emihir0
3
@emihir0,它不在PyPI上。请尝试使用pip install git+https://github.com/SirAnthony/slpp - skovorodkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接