如何将Kivy的maps.kv文件内容转换为嵌套字典?
转换Kivy配置文件maps.kv为嵌套字典
需求说明
需要将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'
期望输出的嵌套字典
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)
完整实现代码
def parse_kv_to_dict(content): # 预处理内容:清理引号、换行、大括号,分割为有效token processed = content.replace('"', '').replace('\n', ' ').replace('{', ' ').replace('}', ' ') tokens = [token for token in processed.split() if token] result = {} current_map = None idx = 1 # 跳过最外层的"map_info" while idx < len(tokens): # 识别地图名称 if tokens[idx] not in ['Map_cooldown', 'Map_installed_date']: current_map = tokens[idx] result[current_map] = {} idx += 1 # 解析属性键值对 else: key = tokens[idx] value = tokens[idx+1] # 尝试转换为整数,失败则保留字符串 try: value = int(value) except ValueError: pass result[current_map][key] = value idx += 2 return result # 读取文件并转换 with open('maps.kv') as f: contents = f.read() dict_contents = parse_kv_to_dict(contents) print(dict_contents)
代码说明
- 内容预处理:通过替换特殊字符、分割字符串,把原文件内容转换成易于遍历的token列表。
- 分层解析:跳过最外层的
map_info标识,依次处理每个地图的名称及其属性键值对。 - 类型适配:对数值类型的属性(如冷却时间)自动转换为整数,时间戳等非数值内容保留字符串格式。
- 字典构建:逐步将解析结果填充到嵌套字典中,最终生成符合需求的结构。
内容的提问来源于stack exchange,提问作者Zaw Lynn Htut
相关产品推荐
相关产品推荐

