解析文本文件不同行的有效方法

时间:2018-09-26 17:56:59

标签: python loops

我有一个文本文件,其中包含以下数据:

1 --- 1 --- 100

2 --- 1 --- 200

3 --- 1 --- 100

1 --- 2 --- 300

2 --- 2 --- 100

3 --- 2 --- 400

我想提取与第二列的不同值相对应的第三列的数据,例如在第三列中添加与第二列中的数字1对应的三个数字,依此类推。我可以逐行循环查找文本,并在每行中找到第三列并添加它们。但这不是我想要的。我应该如何在Python中有效地做到这一点?

1 个答案:

答案 0 :(得分:0)

使用itertools.groupby()

例如,我使用的是您确切的“数据结构” (stackoverflow问题中的一堆文本):

import itertools

data_structure = '''
1 --- 1 --- 100

2 --- 1 --- 200

3 --- 1 --- 100

1 --- 2 --- 300

2 --- 2 --- 100

3 --- 2 --- 400
'''.splitlines()

# create a key function able to extract the data you want to group:
def _key(line):
    return line.strip().split(' --- ')[1] # the 1 here means second column

#cleanup data:
clean_data = (line.strip() for line in data_structure if line.strip())

# then pass it to itertools.groupby:
for key, lines in itertools.groupby(clean_data, key=_key):
    print("Lines that contain number", key, 'in second column:')
    print(', '.join(lines))

结果:

Lines that contain number 1 in second column:
1 --- 1 --- 100, 2 --- 1 --- 200, 3 --- 1 --- 100
Lines that contain number 2 in second column:
1 --- 2 --- 300, 2 --- 2 --- 100, 3 --- 2 --- 400

编辑:既然您已经编辑了问题,并说您有一个文本文件,那么您可以使用它代替data_structure,它将起作用:

data_structure = open('myfile.txt')

其余代码保持不变