码迷,mamicode.com
首页 > 编程语言 > 详细

Python中怎样读取文本.txt格式的文件

时间:2014-12-04 00:57:38      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   使用   sp   for   on   

截取部分内容如下:

10.235186    11.321997
10.122339    11.810993
9.190236     8.904943
9.306371     9.847394
8.330131     8.340352

 怎样将数据转化为矩阵?

第一步使用open()函数打开文件:

1 >>> fileName=D://softwareTool/Python/python_exerciseCode/Chap13_PCA//testSet.txt ;
2 >>> fr=open(fileName);

 

查看类型:

1 >>> fr=open(fileName);
2 >>> type(fr)
3 <class _io.TextIOWrapper>
4 >>> fr
5 <_io.TextIOWrapper name=D://softwareTool/Python/python_exerciseCode/Chap13_PCA//testSet.txt  mode=r encoding=cp936>

 

第2步逐行读取:

如:

1 >>> delim=\t;
2 >>> line0=fr.readlines();
3 >>> type(line0)
4 <class list>
5 >>> line0[0]
6 10.235186\t11.321997\n

 接着进行使用strip和split处理:

1 >>> line1=line0[0].strip()
2 >>> line1
3 10.235186\t11.321997
4 >>> line2=line0[0].strip().split(delim)
5 >>> line2
6 [10.235186, 11.321997]

 第3步将字符串形式转化为float类型的数据形式:

1 >>> line3=[float(line) for line in line2];
2 >>> line3
3 [10.235186, 11.321997]

 

Python中怎样读取文本.txt格式的文件

标签:style   blog   io   ar   color   使用   sp   for   on   

原文地址:http://www.cnblogs.com/yuzhuwei/p/4141713.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!