Python读取数据集并消除数据中的空行
2016-05-03 13:57
621 查看
# -*- coding: utf-8 -*- # @ author hulei 2016-5-3 from numpy import * import operator from os import listdir import sys reload(sys) sys.setdefaultencoding('utf8') # x,y=getDataSet_dz('iris.data.txt',4) def getDataSet(filename,numberOfFeature): #将数据集读入内存 fr = open(filename) numberOfLines = len(fr.readlines()) #get the number of lines in the file file.readlines()是把文件的全部内容读到内存,并解析成一个list returnMat = zeros((numberOfLines,numberOfFeature)) #prepare matrix to return 3代表数据集中特征数目### classLabelVector = [] #prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() #strip() 参数为空时,默认删除空白符(包括'\n', '\r', '\t', ' ') listFromLine = line.split(',') #split 以什么为标准分割一次 分成数组中的每个元素 returnMat[index,:] = listFromLine[0:numberOfFeature] #classLabelVector.append(int(listFromLine[-1])) #append() 方法向列表的尾部添加一个新的元素 if listFromLine[-1] == 'Iris-setosa' : classLabelVector.append(1) elif listFromLine[-1] == 'Iris-versicolor' : classLabelVector.append(2) else: #elif listFromLine[-1] == 'Iris-virginica' : classLabelVector.append(3) index += 1 return returnMat,classLabelVector def getDataSet_dz(filename,numberOfFeature): #改进版,可以消除数据中的空白行 numberOfLines = 0 mx = [] #将数据集 去除空行后存入 fr = open(filename) for line in fr.readlines(): line = line.strip() if line != '' : #去除空白行 numberOfLines+=1 mx.append( line.split(',') ) returnMat = zeros((numberOfLines,numberOfFeature)) classLabelVector = [] for index in range(numberOfLines) : returnMat[index,:] = mx[index][0:numberOfFeature] if mx[index][-1] == 'Iris-setosa' : classLabelVector.append(1) elif mx[index][-1] == 'Iris-versicolor' : classLabelVector.append(2) else: #elif listFromLine[-1] == 'Iris-virginica' : classLabelVector.append(3) return returnMat,classLabelVector
相关文章推荐
- Python Dict all
- 我常用的 Python 调试工具
- [python] 优雅的操作字典
- python脚本管理日记文件
- Python datetime compare
- 使用 Python 进行稳定可靠的文件操作
- python 爬虫实战 抓取学校bbs相关板块的发帖信息
- 『Python』序列学习总结之六——如何命名规范的变量名
- python 的 集合,字典,元组,列表
- 深入浅出设计模式python版——装饰者模式(decorator)
- 【Python】改变对象的字符串显示
- Python整型数与字符串相互转换
- python中else可以和什么搭配
- Python 编写自己的异常
- 利用PYTHON设计计算器功能
- python udp简单示例
- 当我学完Python我学了些什么
- Python实现约瑟夫环问题的方法
- Python实现堆排序的方法详解
- 分分钟学会一门语言之Python篇