参考python读取文件中 的矩阵这篇文章
file = open(‘filename’)
a =file.read()
b =a.split(‘\n’)
for i in range(len(b)):
b[i] = b[i].split()#使用空格分开
len(b[0])
import numpy as np
b = np.array(b)#转成numpy形的
b.shape
type(b)
出现了问题
在执行了下面操作后
b =a.split(‘\n’)
因为文件末尾也有换行符。所以b多了一个元素,是一个空字符。
后续b.shape就不是一个2D矩阵。因此使用Ngl后续画图会有问题。
参考[Python3 中把txt数据文件读入到矩阵中的方法]这篇文章(https://www.php.cn/python-tutorials-394578.html)
在句子分割的时候去掉换行符
from numpy import *
b[i] = b[i].strip('\n').split()
然后定义一个float类型的矩阵来存放数据
A = zeros((len(lines),len(lines[0])),dtype=float)
然后通过循环语句赋值
for i in range(3):
... for j in range(4):
... A[i][j] = lines[i][j]
最终得到了一个float格式的矩阵
第二种方法
file = 'class_attribute_labels_continuous.txt'
cub_attrs = np.loadtxt(file,delimiter=' ')
报错
ValueError: could not convert string to float: ''