无法将字符串转换为浮点数:

时间:2019-03-02 19:50:01

标签: python

此函数未正确将文件转换为矩阵,而我运行代码时却收到错误消息:     returnMat [index ,:] = listFromLine [0:3]

ValueError:无法将字符串转换为浮点数。

def fileToMatrix(filename):
        fr = open(filename)
        numberOfLines = len(fr.readlines())
        returnMat = np.zeros((numberOfLines,3))
        classLabelVector = []
        fr = open(filename)
        index = 0 
        for line in fr.readline():
            line = line.strip() #split in the end of the line
            listFromLine = line.split('\t') # split on tab and make list
            returnMat[index,:] = listFromLine[0:3]
            classLabelVector.append(int(listFromLine[-1]))
            index += 1

        return returnMat, classLabelVector



    if __name__ == '__main__':

        filename ="mydata.txt"
        returnMat,classLabelVector=fileToMatrix(filename)
        print(returnMat)

和数据文件如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

哈哈...错误所在的行:

for line in fr.readline():

我应该使用readlines()函数读取.txt文件的所有行