Python - loading file - dictionary

2019-09-08 07:24发布

问题:

i'm trying to write a function that will turn my text file into a dictionary with subsets. The text document that i have loaded so far is displayed as showed:

101
102
103
201, John Cleese, 5/5/12, 5/7/12
202
203, Eric Idle, 7/5/12, 8/7/12
301
302
303

The outcome of the function should get the information loaded and return it as:

[('101', None), ('102', None), ('103', None),
('201', Guest(John Cleese, 05/05/12, 05/07/12)), ('202', None),
('203', Guest(Eric Idle, 07/05/12, 08/07/12)), ('301', None),
('302', None), ('303', None)]

I've been trying isdigit but to no avail. I managed to get the last room (303) to nearly function though.

def load_rooms(self, filename):
    fd = open(filename, 'rU')
    self._rooms = {}
    for i in fd:
        i = i.rstrip()
        print i

    if i.isdigit():
        self._rooms[i] = None
        print self._rooms
    else:
        print i

displays

101
102
103
201, John Cleese, 5/5/12, 5/7/12
202
203, Eric Idle, 7/5/12, 8/7/12
301
302
303
{'303': None}

Oh wow, i just noticed that the room 303 is shown twice... Well my question is, how would i approach loading the text file? Would i have to make sure that all all the code is in format, or could i just write a function which would turn it into the dictionary with subsets? I'm quite new with dictionaries so a little help would be great. thanks

回答1:

import re

class Guest(object):
  ...

data = []
with open('data.txt') as f:
  for line in f:
    tok = re.split(r'\s*,\s*', line.strip())
    if len(tok) > 1:
      guest = Guest(tok[1], tok[2], tok[3])
    else:
      guest = None
    data.append((tok[0], guest))

print(data)

Implementing the Guest class is left as an exercise for the reader.



回答2:

I'm not sure if you need the re module

try this

def load_file( filename ):
    text = open( "data.txt" ).readlines()
    rooms = {}
    for line in text:
        room_data = line.strip( '\n' ).split( ',' )
        if len( room_data ) > 1:
            #rooms[room_data[0]] = room_data[1:]
            rooms[room_data[0]] = tuple( room_data[1:] )
        else:
            rooms[room_data[0]] = None

    return rooms 

you mention dictionary in your title but your expected outcome is nested lists.

Edit

Answered?