读入txt文件作为每个块的numpy数组

时间:2017-11-02 23:00:19

标签: python numpy readfile

我想从txt文件加载的每个数据块打印一个数组。

我的数据看起来像这样,块之间用白色/空白行隔开:

2 3 4
1 9 3
3 7 2

2 3 2
0 9 8

2 8 2
1 1 1
8 2 0
3 8 2

我想在for循环中打印块。

3 个答案:

答案 0 :(得分:1)

array = []

with open('notepad.txt','r') as file:    
    for line in file:
        if line != '\n':
            array.append(line.strip().split(' '))
        else: 
            print(array)
            array = []      
print(array)

答案 1 :(得分:0)

您可以使用列表理解。

with open('file.txt','r') as file:
   print([' '.join(t).split(' ') for t in [r.split('\n') for r in [e for e in file.read().split('\n\n')]]])

答案 2 :(得分:0)

  

在每个中读取txt文件为 numpy 数组

使用numpy.core.records.fromrecords例程:

import numpy as np

with open('file.txt', 'r') as f:
    data = []
    for l in f:
        if l.strip():
            data.append(l.split())
        else:
            print(np.array(np.core.records.fromrecords(data).tolist(), dtype=np.int), '\n')
            data.clear()
    if data: print(np.array(np.core.records.fromrecords(data).tolist(), dtype=np.int))

输出:

[[2 3 4]
 [1 9 3]
 [3 7 2]] 

[[2 3 2]
 [0 9 8]] 

[[2 8 2]
 [1 1 1]
 [8 2 0]
 [3 8 2]]