Python 有选择地从输入文件复制

Python 有选择地从输入文件复制,python,python-3.x,Python,Python 3.x,我的作业需要3个模块——fileutility、choices和selectiveFileCopy,最后一个模块导入前两个模块 其目的是能够有选择地从输入文件复制文本片段,然后将其写入输出文件,这由选项模块中的“谓词”确定。与中一样,如果存在特定字符串(choices.contains(x)),则复制所有内容(choices.always),或者按长度(choices.shorterThan(x))复制 到目前为止,我只有always()可以工作,但它必须包含一个参数,但我的教授特别指出,参数可

我的作业需要3个模块——fileutility、choices和selectiveFileCopy,最后一个模块导入前两个模块

其目的是能够有选择地从输入文件复制文本片段,然后将其写入输出文件,这由选项模块中的“谓词”确定。与中一样,如果存在特定字符串(choices.contains(x)),则复制所有内容(choices.always),或者按长度(choices.shorterThan(x))复制

到目前为止,我只有always()可以工作,但它必须包含一个参数,但我的教授特别指出,参数可以是任何东西,甚至可以是零(?)。这可能吗?如果是的话,我该如何编写我的定义,使其有效

这个很长问题的第二部分是为什么我的另外两个谓词不起作用。当我用docstests(任务的另一部分)测试他们时,他们都通过了

下面是一些代码:

fileutility(我听说这个函数没有意义,但它是赋值的一部分,所以…)-

选择-

def always(x):
    """
    always(x) always returns True
    >>> always(2)
    True
    >>> always("hello")
    True
    >>> always(False)
    True
    >>> always(2.1)
    True
    """
    return True

def shorterThan(x:int):
    """
    shorterThan(x) returns True if the specified string 
    is shorter than the specified integer, False is it is not

    >>> shorterThan(3)("sadasda")
    False
    >>> shorterThan(5)("abc")
    True

    """
    def string (y:str): 
        return (len(y)<x)
    return string

def contains(pattern:str):
    """
    contains(pattern) returns True if the pattern specified is in the
    string specified, and false if it is not.

    >>> contains("really")("Do you really think so?")
    True
    >>> contains("5")("Five dogs lived in the park")
    False

    """
    def checker(line:str):
        return(pattern in line)
    return checker
到目前为止,我只有一个总是工作的,但它必须有一个 参数,但我的教授特别指出参数可以是 什么都有,甚至什么都没有。这可能吗?如果是,我该如何写我的 定义,使其工作

您可以使用默认参数:

def always(x=None): # x=None when you don't give a argument
    return True
这个很长问题的第二部分是为什么我的另外两个 谓词不起作用。当我用docstests测试它们时(另一部分 他们都通过了

谓词确实有效,但它们是需要调用的函数:

def selectivelyCopy(inputFile,outputFile,predicate):
    linesCopied = 0
    for line in inputFile:
        if predicate(line): # test each line with the predicate function
            outputFile.write(line)
            linesCopied+=1
    inputFile.close()
    return linesCopied
def always(x=None): # x=None when you don't give a argument
    return True
def selectivelyCopy(inputFile,outputFile,predicate):
    linesCopied = 0
    for line in inputFile:
        if predicate(line): # test each line with the predicate function
            outputFile.write(line)
            linesCopied+=1
    inputFile.close()
    return linesCopied