简体   繁体   English

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

[英]Passing a text file in a Python as a function argument

I am working on a data science beginner tutorial and just copied the code. 我正在研究数据科学初学者教程,只是复制了代码。 But I am unable to get rid of the "invalid syntax" error in my function. 但是我无法摆脱函数中的“无效语法”错误。

Already tried to change it into self but then I get an error when I try to "call" the function. 已经尝试将其更改为自己,但是当我尝试“调用”该函数时,我收到错误。

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")

It says that this line: def readDataSet("/Users/leo/Desktop/DS_Code/Example.txt"): 它说这行: def readDataSet("/Users/leo/Desktop/DS_Code/Example.txt"):

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

Thanks, @jonrsharpe & @Iguananaut I edited my code and it works now! 谢谢,@ 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM