Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

Python: Separate text file into list of lists depending on heading

I have a text file in the following format

>heading
A B C D
E F G H
I J K L
>heading
M N O P
Q R S T
>heading
U V W X
Y Z a b
...
...

Each line has the same number of strings except those with the heading and there is not the same number of lines between each ">heading" line.

I would like to read the text file in order to create a Numpy array in the following format:

[[[A, B, C, D], [E, F, G, H], [I, J, K, L]], 
 [[M, N, O, P], [Q, R, T, S]], 
 [[U, V, W, X], [Y, Z, a, b]]]

I thought of checking whether a line is a ">heading" and creating a list of lines that follow it until the next ">heading". Problem is I do not know how to merge those lists into a larger list without it becoming one simple list again.

I have tried the following:

groups = []
with open('textfile.txt', 'r') as f:
    test = '>heading
'
    smallgroup = [test]
    for line in f:
        if line != test:
            smallgroup.append(line)
            groups.append(smallgroup)
        else:
            groups.extend(smallgroup)
question from:https://stackoverflow.com/questions/65902303/python-separate-text-file-into-list-of-lists-depending-on-heading

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

groups = []
with open('textfile.txt', 'r') as f:
    heading = '>heading
'
    smallgroup = []
    for line in f:
        if line == heading:
            if smallgroup:
                groups.append(smallgroup)
            smallgroup = []
        else:
            smallgroup.append(line.strip('
').split(' '))
    groups.append(smallgroup)

print(groups)
# [[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']], [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T']], [['U', 'V', 'W', 'X'], ['Y', 'Z', 'a', 'b']]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...