Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

class - Python - loading file - dictionary

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

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

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...