我有这样的输入:
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,},
。有什么建议吗?
最佳答案
看看这个包裹: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}}
关于python - 将 .lua 表转换为 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838489/