2014-09-24 2 views
0

입력 파일은 다음과 같은 형식을 가지고 짝수 사람을 건너 뛰고 이제코드는

#HEADER1, KEY1=VALUE1 
this is the first section, and it can span 

several lines, until a new section is found (which starts with the # character) 
#HEADER2, KEY1=VALUE1, KEY2=VALUE2, ..., KEYn=VALUEn 
second section here 
again 
it 
can span 
several lines 
#HEADER3... 
a;lkadflkasdf 
... 

#HEADER3 
yet another section 
#HEADERn 
contains the nth section 

I이 섹션 읽기를 시도 다음 코드를

def get_sections(fit): 
    for lno, section in fit: 
    if section.startswith("#"): 
     yield itertools.chain(
     [lno,section], 
     itertools.takewhile(lambda i: not i[1].startswith('#'), fit)) 


def read(self, filename): 

    with open(filename) as fh: 
    fit = enumerate(iter(fh.readline, ''), start=1) 
    for section in get_sections(fit): 

     lino, header, *data = section 
     header = header.strip() 
     print("___"*10) 
     print("<{}>".format(header)) 
     print("[{}]".format(data)) 

를 이 코드는 다음을 출력합니다.

<#HEADER1, KEY1=VALUE1> 
[[(2, ' this is the first section, and it can span\n'), (3, ' \n'), (4, ' several lines, until a new section is found (which starts with the # character)\n')]] 
______________________________ 
<#HEADER3...> 
[[(12, 'a;lkadflkasdf\n'), (13, '...\n'), (14, '\n'), (15, '\n')]] 
inside assign 
______________________________ 
<#HEADERn> 
[[(18, 'contains the nth section')]] 
inside assign 

코드가 섹션을 건너 뛰는 이유는 알 수 없습니다. 첫 번째 섹션을 결론 지으면 두 번째 섹션의 헤더가 이미 읽혀 첫 번째 섹션이 끝난 다음이 줄이 사라지는 것으로 보입니다. 이 코드를 전혀 작동시킬 수 있습니까?

답변

0

iterools.takewhile()은 실제로 조건을 위반하는 요소를 소비합니다. 따라서 귀하의 경우에는 #으로 시작하는 첫 번째 줄, 예를 들어 각각의 짝수 헤더 줄을 사용합니다.

+0

피할 수있는 방법이 있습니까? 어떻게 든 조건을 깨기 전에 반복자의 상태로 돌아갈 수 있을까요? – aaragon