Python: How to loop through blocks of lines

后端 未结 10 1364
青春惊慌失措
青春惊慌失措 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条回答
  •  情话喂你
    2020-11-29 08:26

    Here's another way, using itertools.groupby. The function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False result.

    This is a very convenient way to collect lines into groups.

    import itertools
    
    def isa_group_separator(line):
        return line=='\n'
    
    with open('data_file') as f:
        for key,group in itertools.groupby(f,isa_group_separator):
            # print(key,list(group))  # uncomment to see what itertools.groupby does.
            if not key:
                data={}
                for item in group:
                    field,value=item.split(':')
                    value=value.strip()
                    data[field]=value
                print('{FamilyN} {Name} {Age}'.format(**data))
    
    # Y X 20
    # F H 23
    # Y S 13
    # Z M 25
    

提交回复
热议问题