gpt4 book ai didi

python - 将 .lua 表转换为 python 字典

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:42 26 4
gpt4 key购买 nike

我有这样的输入:

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com