2011-11-06 9 views
0

複数の行にまたがるデータのファイルがあります。データ行の各セクションの前には、ハッシュマーク(#)で始まり、改行( '\ n')、ダッシュ( ' - ')の行、さらに2つの改行が続きます。言い換えればPython 3.2:行のグループを使用して複数行の文字列をセクションに分割する方法

は、ファイルは次のようになります。

# Comment 
# Comment 
data for section 1 
data for section 1 
... 
last line of data for section 1 

-------------------------------------------------- 

# Comment 
# Comment 
data for section 2 
data for section 2 
... 
last line of data for section 2 

-------------------------------------------------- 

... 

私は、私はそれらを個別に処理できるように、このように囲まれている各グループには、このファイルを分割したいです。ファイル処理のための手軽な言語はPython 3.2ですから、この分割を実行する正規表現を作成しようとしました。残念ながら、私はスプリットを動作させることはできません。例えば

、私は正常に無視する行を検索するには、次の正規表現を使用しています

with open('original.out') as temp: 
    original = temp.read() 
print(re.findall(r'^$|^[#-].*$', original, re.MULTILINE)) 

しかし、私はre.split()にこれと同じ正規表現を渡すしようとすると、それは単にファイル全体を返します。

このセクションのリストは、私が必要としている方法で構築することができます。また、正規表現の理解に欠けているもの(またはPythonがどのようにそれらを処理するのか)がわかりません。

答えて

1

迅速かつ汚い発電機ベースのソリューション

from collections import deque 

# yield each section 
def gen_sections(lines): 
    breaker = deque(maxlen=3) 
    section = [] 
    check = [ 
     lambda line: not line.strip(),  # blank 
     lambda line: line.startswith('---'), # dashed line 
     lambda line: not line.strip()  # blank 
    ] 
    for line in lines: 
     line = line.strip() 
     breaker.append(line) 
     section.append(line) 
     if len(breaker) == 3 and all(f(x) for f,x in zip(check, breaker)): 
     yield '\n'.join(section[:-len(breaker)]) 
     section = [] 

# wrap file in this to remove comments 
def no_comments(lines): 
    for line in lines: 
     line = line.strip() 
     if not line.startswith('#'): 
     yield line 

for section in gen_sections(open('file.txt')): 
    print section, '\n' 
関連する問題