如何设置不以“ \t”开头的文件内容?作为键,而那些以“ \t”开头的并以“ \n”结尾作为摆在他们面前的钥匙的价值? [英] How to set contents of a file that don't start with "\t" as keys, and those who start with "\t" and end with "\n" as values to the key before them?

查看:99
本文介绍了如何设置不以“ \t”开头的文件内容?作为键,而那些以“ \t”开头的并以“ \n”结尾作为摆在他们面前的钥匙的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个像这样的字典: {'The Dorms':{'Public Policy':50,'Physics Building':100,'The Commons':120},.. 。}

I want make a dictionary that looks like this: { 'The Dorms': {'Public Policy' : 50, 'Physics Building' : 100, 'The Commons' : 120}, ...}

这是列表:

['The Dorms\n', '\tPublic Policy, 50\n', '\tPhysics Building, 100\n', '\tThe Commons, 120\n', 'Public Policy\n', '\tPhysics Building, 50\n', '\tThe Commons, 60\n', 'Physics Building\n', '\tThe Commons, 30\n', '\tThe Quad, 70\n', 'The Commons\n', '\tThe Quad, 15\n', '\tBiology Building, 20\n', 'The Quad\n', '\tBiology Building, 35\n', '\tMath Psych Building, 50\n', 'Biology Building\n', '\tMath Psych Building, 75\n', '\tUniversity Center, 125\n', 'Math Psych Building\n', '\tThe Stairs by Sherman, 50\n', '\tUniversity Center, 35\n', 'University Center\n', '\tEngineering Building, 75\n', '\tThe Stairs by Sherman, 25\n', 'Engineering Building\n', '\tITE, 30\n', 'The Stairs by Sherman\n', '\tITE, 50\n', 'ITE']

这是我的代码:

def load_map(map_file_name):
    # map_list = []
    map_dict = {}
    map_file = open(map_file_name, "r")
    map_list = map_file.readlines()
    for map in map_file:
        map_content = map.strip("\n").split(",")
        map_list.append(map_content)
    for map in map_list:
        map_dict[map[0]] = map[1:]
    print(map_dict)
if __name__ == "__main__":
    map_file_name = input("What is the map file? ")
    load_map(map_file_name)


推荐答案

您文件的内容显然是文字Python数据,应该使用 ast.literal_eval 来解析它,而不是某些即席方法。

Since your file's content is apparently literal Python data, you should use ast.literal_eval to parse it not some ad-hoc method.

然后,您可以遍历值并处理它们:

Then you can just loop around your values and process them:

def load_map(mapfile):
    with open(mapfile, encoding='utf-8') as f:
        data = ast.literal_eval(f.read())

    m = {}
    current_section = None
    for item in data:
        if not item.startswith('\t'):
            current_section = m[item.strip()] = {}
        else:
            k, v = item.split(',')
            current_section[k.strip()] = int(v.strip())
    print(m)

这篇关于如何设置不以“ \t”开头的文件内容?作为键,而那些以“ \t”开头的并以“ \n”结尾作为摆在他们面前的钥匙的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆