Begin a new file named countchars.py by typing a comment at the top with your name (and lab partner's name if you work together), and the current date. You'll notice the instructions are a bit shorter this time. You are given a problem to solve, but you must figure out how to solve it yourself. Keep in mind what you've learned about top-down programming by stepwise refinement: break the problem into meaningful parts; then solve each part separately. And have fun! |
# strings that must be used for output: prompt = "Enter filename: " titles = "char count\n---- -----" itemfmt = "{0:5s}{1:10d}" totalfmt = "total{0:10d}" whiteSpace = {' ':'space', '\t':'tab', '\n':'nline', '\r':'crtn'}See further instructions about these constants below.
-bash-4.2$ python3 countchars.py
input
to get the filename from the user. Pass the string
named prompt
to this function."http"
then assume it is a local file, and open it
for reading with the built-in open
function. Otherwise import and use the
urllib.request.urlopen
function to open the web page for reading.'A'
and 'a'
as
'a'
).titles
. Then print the table of characters and their
counts in ASCII order, and print the total character count at the bottom.itemfmt
to print each interior row of the table
in the proper format. For example, if c
is a character, and ccount
is its count, then print that row of the table as follows:
print( itemfmt.format(c, ccount) )
whitespace
, then print its description instead of the character itself.
For example:
print( itemfmt.format(whiteSpace[c], ccount) )
totalfmt
to properly print the total character count.
If this count is named total, for example:
print( totalfmt.format(total) )
File/page | Program run |
---|---|
short.txt | short.txt run |
longer.txt | longer.txt run |
http://cs.ucsb.edu/~mikec/cs8/syllabus.html | CS 8 syllabus page run |
turnin P3@cs8c countchars.pyIf you are working with a partner, be sure that both partners names are in a comment at the top of the source code file.