Как установить содержимое файла, который не начинается с «\ t» в качестве ключей, и тех, которые начинаются с «\ t» и заканчиваются на «\ n» в качестве значений ключа перед ними? - PullRequest
0 голосов
/ 06 апреля 2020

Я хочу сделать словарь, который выглядит следующим образом: { '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)

Ответы [ 2 ]

0 голосов
/ 06 апреля 2020

Поскольку содержимое вашего файла, по-видимому, является буквальным Python данными, вы должны использовать ast.literal_eval для его анализа, а не какой-то ad-ho c метод.

Тогда вы можете просто l oop вокруг вашего значения и обработать их:

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)
0 голосов
/ 06 апреля 2020

Вы можете попробовать следующий код, который вернет словарь, как вы описали

def load_map(map_file_name):
    map_dict = {}
    map_file = open(map_file_name, "r")
    map_list = map_file.readlines()
    current_key = ''
    for map in map_list:
        map_content = map.replace("\n", "").replace("\t", "").split(",")
    for map in map_content:
        if len(map) == 1:
            current_key = map[0]
            map_dict[current_key] = {}
        elif len(map) == 2:
            map_dict[current_key][map[0]] = map[1]
    print(map_dict)
if __name__ == "__main__":
    map_file_name = input("What is the map file? ")
    load_map(map_file_name)
...