print header for output

Chris Rebert clp2 at rebertia.com
Sun Jun 19 02:43:07 EDT 2011


On Sat, Jun 18, 2011 at 9:57 PM, Cathy James <nambo4jb at gmail.com> wrote:
> I managed to get output for my function, thanks much  for your
> direction. I really appreciate the hints. Now I have tried to place
> the statement "print ("Length \t" + "Count\n")" in different places in
> my code so that the function can print the headers only one time in
> this manner:
>
> Count  Length
> 4 7
> 8 1
> 12 2
>
>
> Code so far:
> def fileProcess(filename = open('declaration.txt', 'r')):
>
>    """Call the program with an argument,
>    it should treat the argument as a filename,
>    splitting it up into words, and computes the length of each word.
>    print a table showing the word count for each of the word lengths
> that has been encountered."""
>
>    freq = {} #empty dict to accumulate word count and word length
>    print ("Length \t" + "Count\n")
>    for line in filename:
>        punc = string.punctuation + string.whitespace#use Python's
> built-in punctuation and whiitespace
>        for word in (line.replace (punc, "").lower().split()):
>            if word in freq:
>                freq[word] +=1 #increment current count if word already in dict
>
>            else:
>                freq[word] = 1 #if punctuation encountered,
> frequency=0 word length = 0

Un-indent the following 3 lines by 1 level. As I said in my prior
reply, you want the output code to run once per call to your function,
not once per line in the file; since you have said lines within the
`for line in filename` loop body, the latter is currently happening.
Also, in the future, avoid replying to the mailinglist digest, or at
the very least please trim off the irrelevant quoted posts in your
reply.

>        #print ("Length \t" + "Count\n")#print header for all numbers.
>        for word, count in freq.items():
>            print(len(word), count)
>
> fileProcess()

Cheers,
Chris



More information about the Python-list mailing list