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

标签 python dictionary lua

我有这样的输入:

    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/

相关文章:

python - OrderedDict 在 Python 3.7 中会变得多余吗?

c# - 如何在嵌套字典上实现 IEnumerable<T>?

Lua 更改当前/工作目录,Linux(没有 LFS 或任何非标准模块)

python - 如何以优雅且安全(关于Python模块重新加载)的方式使用super()?

python - tkinter 中的检查按钮未将值存储到变量中

python - 如何在 PyQt5 中从头开始制作按钮?

random - 在lua中查找随机数

python - 如何使用 Python 检测 Ubuntu/Linux 上仅 USB 和硬盘的插入?

python - 如何以表格形式和字母顺序打印字典?

lua - 如何使用调试库与所需的 lua 文件的 upvalues 进行交互