鱼C论坛

 找回密码
 立即注册
查看: 3015|回复: 2

[已解决]readLines()问题

[复制链接]
发表于 2017-6-10 20:37:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在看《机器学习实战》一书,ch2的例子,环境是pycharm。文档是源码,导入到pycharm中,运行datingDataMat, datingLabels = kNN.file2matrix('datingTestSet.txt'),出错。
错误信息如下:
>>>datingDataMat, datingLabels = kNN.file2matrix('datingTestSet2.txt')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\kNN.py", line 31, in file2matrix
    for line in fr.readLines():
AttributeError: '_io.TextIOWrapper' object has no attribute 'readLines'

单独写了个文件,试了下readLines()函数,没有问题,能正常运行。请教这个错误是什么原因?
还有一点就是,出错信息写的是line 31,我看了下文档,readLines()函数的调用在40行。难道界面显示的和运行的不是同一个文件?
代码如下 :
from numpy import *
import operator
from os import listdir

def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize,1)) - dataSet
    sqDiffMat = diffMat**2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances**0.5
    sortedDistIndicies = distances.argsort()     
    classCount={}         
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group, labels

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('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector


非常感谢
最佳答案
2017-6-10 20:51:24
你的程序写成了fr.readLines(),而python是区分大小写的,改成fr.readlines()试试。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-6-10 20:51:24 | 显示全部楼层    本楼为最佳答案   
你的程序写成了fr.readLines(),而python是区分大小写的,改成fr.readlines()试试。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-6-10 22:15:17 | 显示全部楼层
冬雪雪冬 发表于 2017-6-10 20:51
你的程序写成了fr.readLines(),而python是区分大小写的,改成fr.readlines()试试。

确实是这个问题。谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-28 00:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表