Python: How to loop through blocks of lines

后端 未结 10 1369
青春惊慌失措
青春惊慌失措 2020-11-29 07:42

How to go through blocks of lines separated by an empty line? The file looks like the following:

ID: 1
Name: X
FamilyN: Y
Age: 20

ID: 2
Name: H
FamilyN: F
A         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 08:17

    import itertools

    # Assuming input in file input.txt
    data = open('input.txt').readlines()
    
    records = (lines for valid, lines in itertools.groupby(data, lambda l : l != '\n') if valid)    
    output = [tuple(field.split(':')[1].strip() for field in itertools.islice(record, 1, None)) for record in records]
    
    # You can change output to generator by    
    output = (tuple(field.split(':')[1].strip() for field in itertools.islice(record, 1, None)) for record in records)
    
    # output = [('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]    
    #You can iterate and change the order of elements in the way you want    
    # [(elem[1], elem[0], elem[2]) for elem in output] as required in your output
    

提交回复
热议问题