Python:TypeError:function至少需要2个参数

时间:2016-04-15 02:35:42

标签: python

当我在书中做一些练习 - 机器学习动作时,在约会匹配问题中,我遇到了以下问题,但我不知道为什么!

Traceback (most recent call last):
  File "(stdin)", line 1, in (module)
  File 'kNN.py', line 27 ,in file2matrix
     fr = open(filename)
TypeError: function takes at least 2 arguments (1 given)

这是我的代码:

    from numpy import *
    import operator
    from os import *

def file2matrix(filename):
    fr = open(filename)
    arrayOLines = fr.readlines()
    numberOfLines = len(arrayOLines)
    returnMat = zeros((numberOfLines,3))
    classLabelVector = []
    index = 0
    for line in arrayOLines:
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector

我做了修改,但问题仍然存在! 它描述了kNN算法。

1 个答案:

答案 0 :(得分:3)

您正在使用os内的内置函数覆盖内置的open函数:

In [1]: open?
Docstring:
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the
preferred way to open a file.  See file.__doc__ for further information.
Type:      builtin_function_or_method

In [2]: import os

In [3]: os.open?
Docstring:
open(filename, flag [, mode=0777]) -> fd

Open a file (for low level IO).
Type:      builtin_function_or_method

这就是为什么你应该避免from somewhere import *