解析文本文件,存储值并创建列表并将其保存到字典python中

时间:2015-07-15 14:37:39

标签: python-2.7

我有这个文本文件:

Trx/Sec for Group = test1
1012.2481
1998.4325
2144.5587
1899.6620
2040.6039
Trx/Sec for Group = test2
1071.7884
2200.5912
2441.3168
2333.9467
2298.3223
Trx/Sec for Group = test3
1198.8516
3105.0714
2716.3977
3643.8187
3488.8449
Trx/Sec for Group = test4
1189.2456
2736.2144
3258.7045
3161.7456
3178.8911
Trx/Sec for Group = test5
1289.8055
3153.5590
3974.3909
3779.2508
3448.0718
Trx/Sec for Group = test6
1026.1191
2409.5093
2751.6694
2657.5202
2439.7788
Trx/Sec for Group = test7
566.9536
1542.1786
1614.5561
1452.0273
1568.4051

如何解析每一行,当我看到组时,存储该组并将其保存在列表中并将其保存到字典中

这就是我的尝试:

logfile = open("logfile.txt", "r").readlines()
KEYWORDS = ['Group']
counterline = []
counter = 0
for line in logfile:
    for word in line.split():
        counter+=1
            if word in KEYWORDS:
                counterline.append(counter)
                print word
                  print KEYWORDS
                  print counterline

1 个答案:

答案 0 :(得分:0)

myDict = {}
with open('a.txt') as f:
    currentList = []
    for line in f:
        if 'Group' in line:
            if currentList:
                myDict[currentGroup] = currentList
                currentList = []
            currentGroup = line[line.index('=')+1:].strip()
        else:
            currentList.append( float(line.strip()) )
    if currentList:
        myDict[currentGroup] = currentList

print myDict

<强>输出:

 {'test1': [1012.2481, 1998.4325, 2144.5587, 1899.662, 2040.6039],
 'test2': [1071.7884, 2200.5912, 2441.3168, 2333.9467, 2298.3223],
 'test3': [1198.8516, 3105.0714, 2716.3977, 3643.8187, 3488.8449],
 'test4': [1189.2456, 2736.2144, 3258.7045, 3161.7456, 3178.8911],
 'test5': [1289.8055, 3153.559, 3974.3909, 3779.2508, 3448.0718],
 'test6': [1026.1191, 2409.5093, 2751.6694, 2657.5202, 2439.7788],
 'test7': [566.9536, 1542.1786, 1614.5561, 1452.0273, 1568.4051]}