python如何导入txt文件-数据从txt文本导入python
机器学习实战 p21
源代码:
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split(' ')
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1])) 此句报错
index += 1
return returnMat,classLabelVector
报错如下:
>>> mat,label = kNN.file2matrix('datingTestSet.txt')
Traceback (most recent call last):
File "", line 1, in
File "kNN.py", line 50, in file2matrix
classLabelVector.append(int(listFromLine[-1]))
ValueError: could not convert string to int: largeDoses
解决方法:
listFromLine[-1]的值形似如下格式,带有回车换行符
largeDoses
smallDoses
didntLike
didntLike
didntLike
要将字母字符串转换为int类型是不可能的。
作者定义largeDoses 为3,smallDoses 为2,didntLike为1
于是笔者增加了一个字典类型
d = {'didntLike': 1, 'smallDoses': 2, 'largeDoses': 3}
通过d[listFromLine[-1]]得到对应的label
更改后的代码如下:
rf.py
from numpy import *
import operator
from os import listdir
def rf(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
d = {'didntLike': 1, 'smallDoses': 2, 'largeDoses': 3}
classLabelVector = []
index = 0
fr = open(filename)
for line in fr.readlines():
listFromLine = line.split(' ')
returnMat[index,:] = listFromLine[0:3]
listFromLine[-1] = listFromLine[-1][0:-2] #去除尾端的回车换行符
classLabelVector.append(d[listFromLine[-1]]) #取到字典中对应的label值
index += 1
return returnMat,classLabelVector
画图:
import rf
mat,label = rf.rf('datingTestSet.txt')
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
>>> ax1 = fig.add_subplot(2, 2, 1)
>>> ax1.scatter(mat[:,0],mat[:,1])
>>> ax2 = fig.add_subplot(2, 2, 2)
>>> ax2.scatter(mat[:,1],mat[:,2])
from numpy import array #需要自己导入array,否则会报错
>>> ax3 = fig.add_subplot(2, 2, 3)
>>> ax3.scatter(mat[:,0],mat[:,1],15.0*array(label),15.0*array(label))
ax4 = fig.add_subplot(2, 2, 4)
ax4.scatter(mat[:,1],mat[:,2],15.0*array(label),15.0*array(label))
plt.show()
python如何导入txt文件-数据从txt文本导入python相关推荐
- python接口自动化参数化_Python读取txt文件数据的方法(用于接口自动化参数化数据)...
小试牛刀: 1.需要python如何读取文件 2.需要python操作list 3.需要使用split()对字符串进行分割 代码运行截图 : 代码(copy) #encoding=utf-8 #1.r ...
- 【python图像处理】txt文件数据的读取与写入
在使用python进行数据和图像处理的过程中,经常会遇到从txt文件中读取数据.已经将处理过程中的矩阵数据写入到txt文件的情形,如在伪彩映射中读取颜色映射表. 下面介绍几种我平时常用的txt文件数据 ...
- python不同数据的读入_python读写不同编码txt文件_python读写txt文件
python读写不同编码txt文件_python读写txt文件 以后整理规范 [python] view plaincopy import os import codecs filenames=os. ...
- 导入 txt 文件数据到 MySQL 表
导入 txt 文件数据到 MySQL 表 需求:导入数据到 MySQL 表中 操作: 新建一个 .txt 文件 新建一个表 右击表选择导入向导 选择导入类型为文本文件(*.txt) 选择创建的 .tx ...
- mysql 通过load data local infile导入txt文件数据
如果一次性需要插入大批量数据,使用insert语句插入性能较低 可以使用MySQL数据库提供的load 指令进行数据插入: # 执行load指令将准备好的数据,加载到表结构中 load data lo ...
- [Excel知识技能] Txt文件数据批量导入Excel
记录(日期: 2022/5/20) 在实际工作中,遇到过将Txt格式的数据导入到Excel中,为此特意记录以下操作过程,便于日后的回顾和学习 需要导入的文本文件如下图所示: Txt文本数据源 Site ...
- ADF txt文件数据导入table
创建表 CREATE TABLE ALS_STAFF ( ID NUMBER(3,0), FIRST_NAME VARCHAR2(20 BYTE), LAST_NAME VARCHAR2(30 BYT ...
- python读取txt文件并求和,Python读取txt文件数据的方法(用于接口自动化参数化数据)...
小试牛刀: 1.需要python如何读取文件 2.需要python操作list 3.需要使用split()对字符串进行分割 代码运行截图 : 代码(copy) #encoding=utf-8 #1.r ...
- matlab读取TXT文件数据,二进制文件数据
1. maltab自带工具 选择数据文件后 可以看到如下界面 可以根据实际选择分隔符,一般是空格或者逗号 有些第一行还有变量名,所以一般舍去第一行等 最后点击导入所选内容即可 优缺点 不能打开太大的文 ...
最新文章
- java 图片处理 图片缩略图,java怎么生成图片缩略图,缩小图片,高清图片缩小
- c++类与类之间关系
- 对某bc站的一次渗透测试
- php的cookie变量作用,PHP语言中cookie的作用
- js 字符串插入_前端利器React,为什么推荐JSX来替换JS
- mysql从5.1.63升级到5.6.20出现的问题
- docker network bridge模式,自定义(一)
- mysql pk_mysql_1
- 抽奖砍价之类以均值为基础的波动算法 demo版本
- 深度学习蚕食软件,十年内大部分软件工作不再涉及编程
- 【2011-2012 ACM-ICPC Pacific Northwest Regional Contest】Collateral Cleanup【建图拓扑排序】
- Cost Function of Support Vector Machine
- shopex操作记录
- android捕获按键广播,Android 解决监听home键的几种方法
- 【转载】uTorrent缓存设置,防止出现磁盘负荷100%
- PDF转成Word或PPT后不能修改的原因和解决方法
- IP多播(计算机网络-网络层)
- @Transactional注解用法
- “果粉的倒戈”与荣耀的较量
- [zz]2008好莱坞进口大片全扫描
热门文章
- 20172301 《程序设计与数据结构》第七周学习总结
- 【模板】折线分割平面
- 20170817 - 今日技能封装 - A
- Rhythmk 一步一步学 JAVA(11)Ibatis 环境配置
- 深入浅出mfc学习笔记——六大关键技术之仿真_运行时和动态创建
- python一点基础都没有的怎么办-Python基础知识细节点总结,零基础一分钟也能掌握...
- 小孩学python有意义吗-世界冠军教练告诉你:少儿编程这些坑,能不踩就别踩!...
- python是什么语言开发的-少儿编程有什么好处?儿童编程课程学习Python的4大原因...
- python的翻译-用Python做一个简单的翻译工具
- 想学python看什么书-请问想学python和JAVA得看什么书?