2016-10-03 410 views
2

我有这种投入:转换.lua表Python字典

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

错误(invalid syntax)是{"b1", "b2" : true,},。任何建议?

+0

你要转换'“B1”''成“B1”:None'或类似的东西 - 字典不能没有价值的关键。 BTW'{“a1”,}'不是字典而是'set()' - 尝试'print(type {{a1“,})'',您会得到'' – furas

+0

如何将''b1”'转换为''b1':None''给定了上面我已经提到的函数?我假设一些模式匹配会被用来找到''something','并用'替换掉':None,'',但我不确定如何做到这一点 – emihir0

+0

只是好奇,为什么你想用它与Python?:) – warspyking

回答

4

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

我在安装时遇到问题。 IE浏览器。 pip install slpp告诉我没有这样的软件包,并且在他们的github上我看不到任何“安装”指南。任何建议? – emihir0

+1

@ emihir0,它不在PyPI上。试试这个'pip install git + https:// github.com/SirAnthony/slpp'。 – skovorodkin

+0

作品,谢谢。 @skovorodkin – emihir0