This assignment is about looping over lists, reading and writing files, and using functions to transform data from one form to another. It's also about reading code provided to you and trying to fit new code into the existing code. This is a skill that's needed in writing all kinds of programs. You have to do three things:
tansform_file
(see
it in FileTransform.py) to see the
steps taken when the program is run:
You have to write code that accomplishes the last two steps by adding
code to the functions transform
and
write_words
respectively. Do these one at a time,
working on transform
first.
You can test transform
by converting words to upper-case.
get_words
, stored in
variable words
in the function
transform_file
, is this list of lists.
The list words[0]
is the first line of the file read, with
each word on that line an element of words[0]
. Thus to
print the second line of the file read, which is stored in
words[1]
you could use this code (note that the comma keeps
the words printed on one line, the print
after the loop
moves the console-cursor to the next line.
transform
transform
takes the list of lists and returns
a copy, a new list, of transformed words. The parameter
lines
is the list of lists, e.g., lines[0]
is a list of the words on the first line of the file read. The value
returned is also a list of lists, e.g., with copy[0]
being the list of words on the first line that have been
transformed.
This means if lines[0]
is ["The", "big", "dog",
"barked"]
then copy[0]
would be
["THE", "BIG", "DOG", "BARKED"]
if the uppercase transform
is chosen.
The second parameter to the function transform
is actually
the function to apply to each word -- instead of passing a list, a
string, or an int --- the code passes a function like
transform_upper
or transform_pig
. This
parameter
is named func
-- to apply it you could write this list
comprehension, for example, to every word in
copy[index]
func(w)
-- remember that func
is
actually something like transform_pig
.
write_words
file
--- this is a bad name as we
discussed in class because it's a type in Python).
The code you're given prints every word, a space after every word, and
puts the words on a line from the file on a line of the
console. You need to call file.write
appropriately to
mirror what's done on the console: words, spaces, and newlines.
choose_transform
.