在Python中将文本文件作为函数参数传递

时间:2019-05-18 11:26:28

标签: python python-3.x

我正在研究数据科学入门教程,只是复制了代码。但是我无法摆脱函数中的“无效语法”错误。

已经尝试将其更改为self,但是当我尝试“调用”该函数时出现错误。

class DataAlgorithmus:
    def readDataSet("/Users/leo/Desktop/DS_Code/Example.txt"):

        fr = open("/Users/leonard/Desktop/DS_Code/Example.txt")  
        numberOfLines = len(fr.readlines())  
        returnMat = numpy.zeros((numberOfLines-1, 3))
        classLabelVector = []
        classColorVector = []
        fr = open("/Users/leonard/Desktop/DS_Code/Example.txt") 
        index = 0

        for line in fr.readlines(): 
            if index != 0:         
                line = line.strip()
                listFromLine = line.split('\t')
                returnMat[index-1, :] = listFromLine[1:4]

                classLabel = listFromLine[4]
                if classLabel == "Buero":
                    color = 'yellow'
                else:
                    color = 'blue'

                classLabelVector.append(classLabel)
                classColorVector.append(color)
            index += 1

        return returnMat, classLabelVector, classColorVector

    dataSet, classLabelVector, classColorVector = readDataSet("/Users/leonard/Desktop/DS_Code/Example.txt")

它说这一行: def readDataSet("/Users/leo/Desktop/DS_Code/Example.txt"):

具有以下错误: invalid syntax (<unknown>, line 3) pylint(syntax-error) [3,1]

1 个答案:

答案 0 :(得分:0)

谢谢@jonrsharpe和@Iguananaut我编辑了代码,现在可以使用了!

def readDataSet(self, filename):

    fr = open(filename)  
    numberOfLines = len(fr.readlines())  
    returnMat = numpy.zeros((numberOfLines-1, 3))
    classLabelVector = []
    classColorVector = []
    fr = open(filename) 
    index = 0

    for line in fr.readlines(): 
    if index != 0:         
            line = line.strip()
            listFromLine = line.split('\t')
            returnMat[index-1, :] = listFromLine[1:4]

            classLabel = listFromLine[4]
            if classLabel == "Buero":
                color = 'yellow'
            else:
                color = 'blue'

            classLabelVector.append(classLabel)
            classColorVector.append(color)
        index += 1

    return returnMat, classLabelVector, classColorVector

dataSet, classLabelVector, classColorVector = readDataSet("/Users/leonard/Desktop/DS_Code/Example.txt")