[英]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.