读取文本文件的块文本 python

Read block Text of a text file python

输入文件 - input.csv

#######A Result:#########
2016-07-27   bar       51     14
2015-06-27   roujri    30     86
#######B Result:#########
2016-08-26   foo       34      83
2016-08-26   foo       34      83
#########################

输出结果

A result:
     Col-1: 81
     Col-2: 100
B result:
     Col-1: 68
     Col-2: 166

我正在尝试根据以上输入输出解决一个问题。到目前为止,我只能阅读第一块文本。我想要更通用的函数,所以我可能只会初始化需要在块内读取的变量,而不是硬编码(例如 #######A Result:#########),并将块信息传递给另一个函数,该函数将对值进行求和。任何建议将不胜感激。谢谢 :)

import re
def reading_block_text_file(infile):
     with open(infile) as fp:
         for result in re.findall('#######A Result:#########(.*?)#######B Result:#########', fp.read(), re.S):
             print result,

reading_block_text_file(input_file)

加入一点正则表达式:

$ cat a
#######A Result:#########
2016-07-27   bar       51     14
2015-06-27   roujri    30     86
#######B Result:#########
2016-08-26   foo       34      83
2016-08-26   foo       34      83
#########################
$ cat a.py
import re
col_names = ['abc', 'xyz']
with open("/tmp/a", "r") as f:
    tables = re.findall(r'#+(\w+ Result:)#+([^#]*)', f.read(), re.S)
    for table in tables:
        name = table[0]
        rows = table[1].strip().split('\n')
        print name
        for i in range(len(col_names)):
            print "\t{}: {}".format(col_names[i], sum(map(lambda x: int(x.split()[i + 2]), rows)))
$ python a.py
A Result:
    abc: 81
    xyz: 100
B Result:
    abc: 68
    xyz: 166

正则表达式解释:

#+(\w+ Result:)#+([^#]*)

Debuggex Demo