繁体   English   中英

python 将.kv(Kivy)文件的内容转换为字典

[英]python convert contents of .kv (Kivy) file to dictionary

我想将“maps.kv”文件内容转换成字典。

我有键值文件调用“maps.kv”

内容看起来像这样。

"map_info"
{
  "map_A"
  {
    "Map_cooldown"        "100"
    "Map_installed_date"  "1659754646"
  }
  "map_B"
  {
    "Map_cooldown"        "200"
    "Map_installed_date"  "1659754646"
  }
}

以上内容无格式

b'"map_info"\n{\n\t"map_A"\n\t{\n\t\t"Map_cooldown"\t\t"100"\n\t\t"Map_installed_date"\t\t"1659754646"\n\t}\n\t"map_B"\n\t{\n\t\t"Map_cooldown"\t\t"200"\n\t\t"Map_installed_date"\t\t"1659754646"\n\t}\n}\n'

我想将上面的“内容”转换为嵌套字典

欲望output

dict_contents = { 'map_A': { 'Map_cooldown':100, 'Map_installed_date':'1659754646'},
                  'map_B': { 'Map_cooldown':200, 'Map_installed_date':'1659754646'}}

到目前为止,这是我的代码

with open('maps.kv') as f:
contents = f.read()
print(contents)

检查下面的代码=>import ast<=:

xx=b'"map_info"\n{\n\t"map_A"\n\t{\n\t\t"Map_cooldown"\t\t"100"\n\t\t"Map_installed_date"\t\t"1659754646"\n\t}\n\t"map_B"\n\t{\n\t\t"Map_cooldown"\t\t"200"\n\t\t"Map_installed_date"\t\t"1659754646"\n\t}\n}\n'

    xx1 = [i.replace('\n','') for i in xx.decode('UTF-8').splitlines()][1:]

    ast.literal_eval(','.join(xx1).\
                     replace(',\t','').\
                     replace('\t\t',':').\
                     replace('{\t',':{').\
                     replace('\t',',').\
                     replace('}"','},"').\
                     replace('},}','}}'))

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM