My assignment calls for 3 modules- fileutility, choices, and selectiveFileCopy, the last of which imports the first two.
The purpose is to be able to selectively copy pieces of text from an input file, then write it to an output file, determined by the “predicate” in the choices module. As in, either copy everything (choices.always), if a specific string is present(choices.contains(x)), or by length (choices.shorterThan(x)).
So far, I have only the always() working, but it must take in one parameter, but my professor specifically stated the parameter could be anything, even nothing(?). Is this possible? If so, how do I write my definition so that it works?
The second part of this very long question is why my other two predicates don’t work. When I tested them with docstests(another part of the assignment), they all passed.
Here’s some code:
fileutility(I’ve been told this function is meaningless, but its part of the assignment so…)-
def safeOpen(prompt:str, openMode:str, errorMessage:str ):
while True:
try:
return open(input(prompt),openMode)
except IOError:
return(errorMessage)
choices-
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))
You can use a default argument:
Your predicates do work, but they are functions that need to be called: