Python - 加载文件 - 字典 [英] 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)]
我一直在尝试isdigit,但没有效果。我设法得到最后一个房间(303)几乎运作。
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
显示
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}
哦,哇,我只是注意到房间303显示两次...我的问题是,我将如何加载文本文件?我需要确保所有的所有代码是在格式,或者我可以只写一个函数,将它变成字典与子集?我对字典很新,所以一点帮助将是伟大的。感谢
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
推荐答案
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)
c $ c>来宾课程留给读者做练习。
Implementing the Guest
class is left as an exercise for the reader.
这篇关于Python - 加载文件 - 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!