我的作业需要3个模块 - 文件用途,选择和selectiveFileCopy,其中最后一个导入前两个。
目的是能够有选择地从输入文件中复制文本片段,然后将其写入输出文件,由"谓词"在选择模块中。如同,请复制所有内容(choices.always),如果存在特定字符串(choices.contains(x))或长度(choices.shorterThan(x))。
到目前为止,我只有always()工作,但它必须接受一个参数,但我的教授明确指出参数可以是任何东西,甚至没有(?)。这可能吗?如果是这样,我如何编写我的定义以使其有效?
这个很长的问题的第二部分是为什么我的另外两个谓词不起作用。当我用docstests(作业的另一部分)测试它们时,它们都通过了。
这里有一些代码:
fileutility(我已经被告知这个函数没有意义,但是它的一部分是如此......) -
def safeOpen(prompt:str, openMode:str, errorMessage:str ):
while True:
try:
return open(input(prompt),openMode)
except IOError:
return(errorMessage)
选择 -
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
selectiveFileCopy -
import fileutility
import choices
def selectivelyCopy(inputFile,outputFile,predicate):
linesCopied = 0
for line in inputFile:
if predicate == True:
outputFile.write(line)
linesCopied+=1
inputFile.close()
return linesCopied
inputFile = fileutility.safeOpen("Input file name: ", "r", " Can't find that file")
outputFile = fileutility.safeOpen("Output file name: ", "w", " Can't create that file")
predicate = eval(input("Function to use as a predicate: "))
print("Lines copied =",selectivelyCopy(inputFile,outputFile,predicate))
答案 0 :(得分:1)
到目前为止,我只有always()工作,但它必须接受一个 参数,但我的教授明确指出参数可能是 什么,甚至没什么(?)。这可能吗?如果是这样,我该怎么写我的 定义,以便它的工作?
您可以使用默认参数:
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