0

我想解析一个看起来像这样的文件:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA


AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
HEADER
body
body
body
FOOTER
BLABLABLABLA
BLABLABLABLA
BLABLABLABLA

我想提取 HEADER 和 FOOTER 之间存在的内容。每个 HEADER 和 FOOTER 之间的行数可以变化,内容本身也可以变化,我编写了以下代码来提取它:

   fd=open(file,"r")
    for line in fd:
        if not start_flag:
            match = re.search(r'.*HEADER.*',line)
            if not match:
                continue
            else:
                body=body+line+"\n"
                start_flag=True
        else:
            match_end = re.search(r'.*FOOTER.*',line)
            if not match_end:
                body=body+line+"\n"
                continue
            else:
                body=body+line+"\n\n"
                break
   print body

这是使用 python 从文件中提取内容的最佳方法吗?解决此类问题的其他方法是什么?

4

3 回答 3

5
from itertools import groupby

with open(f, "r") as fin:
    groups = groupby(fin, key=lambda k:k.strip() in ("HEADER", "FOOTER"))
    any(k for k,g in groups)
    content = list(next(groups)[1])
print content
于 2013-04-10T23:09:03.240 回答
4

这是一种使用方法itertools

from itertools import takewhile, dropwhile

with open("myfile.txt") as f:
    starting_iterator = dropwhile(lambda x: x.strip() != 'HEADER', f)
    next(starting_iterator, None)
    contents = takewhile(lambda x: x.strip() != 'FOOTER', starting_iterator)    
    print list(contents)
于 2013-04-10T23:09:49.643 回答
0

由于我的评论遭到反对,我不妨展示一下我是如何做到的(无需在内存中构建列表——这就是迭代器的用途:

import itertools as it

def contents(source):
    return it.takewhile(lambda x: "FOOTER" != x.strip(),
        it.islice(
            it.dropwhile(lambda x: "HEADER" != x.strip(), source),
        1, None) )

with open("testfile") as f:
    for line in contents(f):
        # Do your stuff here....
于 2013-04-11T10:04:01.597 回答