Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...