read file into array separated by paragraph Python

后端 未结 7 982
半阙折子戏
半阙折子戏 2021-02-08 22:11

I have a text file, I want to read this text file into 3 different arrays, array1 array2 and array3. the first paragraph gets put in array1, the second paragraph gets put in arr

7条回答
  •  时光取名叫无心
    2021-02-08 22:29

    import itertools as it
    
    
    def paragraphs(fileobj, separator='\n'):
        """Iterate a fileobject by paragraph"""
        ## Makes no assumptions about the encoding used in the file
        lines = []
        for line in fileobj:
            if line == separator and lines:
                yield ''.join(lines)
                lines = []
            else:
                lines.append(line)
        yield ''.join(lines)
    
    paragraph_lists = [[], [], []]
    with open('/Users/robdev/Desktop/test.txt') as f:
        paras = paragraphs(f)
        for para, group in it.izip(paras, it.cycle(paragraph_lists)):
            group.append(para)
    
    print paragraph_lists
    

提交回复
热议问题