- use
$ man wc
at the command line to read the manual forwc
- it returns the number of lines, words, and bytes (characters) of a file
example:
$ wc test_files/constitution.txt
872 7652 45119 test_files/constitution.txt
First, as with just about any program you write,
it's useful thinking about what the INPUT
(s) and OUTPUT
(s) should be.
In this case,
- INPUT
: a file path
- OUTPUT
s:
- count of lines
- count of words
- count of bytes
Note: the wc
utility actually allows you to provide many files as inputs
and returns counts for each of them.
In this assignment, we won't worry about that though.
Next, we should write out what our code will do in plain language.
In other words, given our INPUT
s, how do we get to our OUTPUT
s.
In class, here's what we came up with:
- Get our input file as a commandline argument (probably using
argparse
) - Open the file
- Initialize variables for
lines
,words
, andbytes
- Read the file line by line
- for each line, add
1
to thelines
variable - to count the number of words, use
.split()
on the line, then uselen()
on the list that's returned- don't forget to add that number to the
words
variable!
- don't forget to add that number to the
- to count the number of bytes, use
len()
on the line string itself- don't forget to add that number to the
bytes
variable!
- don't forget to add that number to the
- for each line, add
- Once we've read through the file, print the values of
lines
,words
, andbytes
to the screen - Close the file