我有一个这样的文件:
group #1
a b c d
e f g h
group #2
1 2 3 4
5 6 7 8
我怎样才能把它变成这样的字典:
{'group #1' : [[a, b, c, d], [e, f, g, h]],
'group #2' :[[1, 2, 3, 4], [5, 6, 7, 8]]}
答案 0 :(得分:3)
file = open("file","r") # Open file for reading
dic = {} # Create empty dic
for line in file: # Loop over all lines in the file
if line.strip() == '': # If the line is blank
continue # Skip the blank line
elif line.startswith("group"): # Else if line starts with group
key = line.strip() # Strip whitespace and save key
dic[key] = [] # Initialize empty list
else:
dic[key].append(line.split()) # Not key so append values
print dic
输出:
{'group #2': [['1', '2', '3', '4'], ['5', '6', '7', '8']],
'group #1': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]}
答案 1 :(得分:1)
迭代文件,直到找到“group”标记。使用该标记向字典添加新列表。然后将行添加到该标记,直到您点击另一个“组”标记。
未测试
d = {}
for line in fileobject:
if line.startswith('group'):
current = d[line.strip()] = []
elif line.strip() and d:
current.append(line.split())