【问题标题】:Python: Separate text file into list of lists depending on headingPython:根据标题将文本文件分成列表列表
【发布时间】:2021-04-30 07:02:33
【问题描述】:

我有一个如下格式的文本文件

>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
...
...

除了带有标题的字符串外,每一行都有相同数量的字符串,并且每个“标题”行之间的行数不同。

我想读取文本文件以创建以下格式的 Numpy 数组:

[[[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]]]

我想检查一行是否是“标题”并创建一个跟随它的行列表,直到下一个“标题”。问题是我不知道如何将这些列表合并到一个更大的列表中,而不会再次变成一个简单的列表。

我尝试了以下方法:

groups = []
with open('textfile.txt', 'r') as f:
    test = '>heading\n'
    smallgroup = [test]
    for line in f:
        if line != test:
            smallgroup.append(line)
            groups.append(smallgroup)
        else:
            groups.extend(smallgroup)

【问题讨论】:

  • 您不能拥有该格式的 numpy 数组,因为它们的形状并不完全相同……您可以拥有一个列表列表,尽管这似乎是您正在创建的。 .. 如果文件不是那么“大”,您可以随时阅读text = f.read(),然后使用:groups = [[line.split() for line in group.splitlines()] for group in text.split('>heading\n') if group] 将其拆分

标签: python list numpy append


【解决方案1】:

试试这个:

groups = []
with open('textfile.txt', 'r') as f:
    heading = '>heading\n'
    smallgroup = []
    for line in f:
        if line == heading:
            if smallgroup:
                groups.append(smallgroup)
            smallgroup = []
        else:
            smallgroup.append(line.strip('\n').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']]]

【讨论】:

    猜你喜欢
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 2018-03-25
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多