簡體   English   中英

根據頁眉和頁腳模式在python中搜索文件

[英]search files in python based on header and footer patterns

我想解析一個看起來像這樣的文件:

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從文件中提取內容的最佳方法嗎? 解決此問題的其他方法有哪些?

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

這是使用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)

自從我的評論被推后,我不妨展示一下我將如何做(無需在內存中建立列表,這就是迭代器的作用):

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....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM