读取文本文件的块文本python

2024-10-03 23:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

输入文件-输入.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
#########################

输出结果

^{pr2}$

我正试图根据上述输入、输出来解决一个问题。到目前为止,我只能阅读第一块文本。我想要更通用的函数,所以我可能只初始化需要在块内读取的变量,而不是硬编码(例如#######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)

Tags: 文件csv函数textrefoobarresult
1条回答
网友
1楼 · 发布于 2024-10-03 23:22:43

加入一点正则表达式:

$ 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

正则表达式解释:

^{pr2}$

Regular expression visualization

Debuggex Demo

相关问题 更多 >