More Transformations
Here's some example code for you to reference as you work through the assignment:
Assignment
Complete the doc_format_checker_and_converter
function.
It takes a conversion_function
and a list of valid_formats
as parameters. It should return a new function that takes two parameters of its own:
filename
: The name of the file to be convertedcontent
: The content (body text) of the file to be converted
Tip
The capitalize_content
and reverse_content
are "conversion functions" that will be passed into our doc_format_checker_and_converter
function by the tests.
Solution
The solution defines the doc_format_checker_and_converter
function, which takes two parameters:
conversion_function
: A function that will convert the content of a file if its format is valid.valid_formats
: A list of valid file extensions.
What's happening:
Inside
doc_format_checker_and_converter
, you define a new function calledchecker
. This function accepts two parameters:filename
: The name of the file to be converted.content
: The content of the file to be converted.
The
filename.split(".")
line splits the filename into the base name (file_name
) and its extension (extension
).If the
extension
is in thevalid_formats
list, thechecker
function will call theconversion_function
with thecontent
as an argument and return the result of the conversion.If the
extension
is not in thevalid_formats
list, aValueError
is raised with the message"invalid file format"
.Finally,
doc_format_checker_and_converter
returns thechecker
function.
This approach allows you to dynamically check the file format and apply different conversion functions to the content depending on the format.
Example Usage:
In the code above, when you call checker("document.txt", "hello world")
, it checks the file extension, finds it in valid_formats
, and calls capitalize_content
. If the extension is not valid, like in checker("document.pdf", "hello world")
, it raises a ValueError
.
Last updated