[Tutor] Lance E Sloan"help"

S A buc40@bemail.org
Wed, 21 Aug 2002 13:01:32 -0700


Ok. I'm not Lance , but I'll give it a shot:
>
># line/word counter  
>
>def getStuff(file):
>    info = open(file, 'r')
>    infolines = info.readlines()
>    linenum = 1
>    for line in infolines:
>        words = line.split(' ')
>        print "Line %d contains %d words" % (linenum, len(words))
>        linenum += 1
>
>file = raw_input("Enter the filename: ")
>getStuff(file)
>
>
>
>Enter file name:
>> testfile.txt
>
>
>LINE#  WORDS
>--------------------
>1      20 words
>2      25 words
>3      30 words
>4      25 words
>--------------------
>Summary:
>4 lines, 100 words, Avg: 25 words/line

First let's look at why your for loop does not work:

    1. import string
    2. change the for loop to the following:

>>> for lines in infolines:
...     word = string.split(lines)
...     print "Line %d contains %d words" % (linenum, len(word))
...     linenum += 1
... 
Line 1 contains 8 words
Line 2 contains 0 words
Line 3 contains 1 words
Line 4 contains 0 words
Line 5 contains 13 words
Line 6 contains 5 words
Line 7 contains 1 words
Line 8 contains 7 words
Line 9 contains 0 words
Line 10 contains 2 words
Line 11 contains 0 words

Now the rest is formatting your print and doing some math on lines and words.

Make sure you place the print statement for:
LINE#  WORDS
--------------------

--------------------
Summary:
4 lines, 100 words, Avg: 25 words/line

Outside of the iteration. And all of the other data can be printed inside the for loop.

Hope this helps some.
Good Luck.

SA




"I can do everything on my Mac that I used to do on my PC, plus alot more ..."

-Me

------------------------------------------------------------
Free, BeOS-friendly email accounts: http://BeMail.org/
BeOS News and Community: http://www.BeGroovy.com/


---------------------------------------------------------------------
Express yourself with a super cool email address from BigMailBox.com.
Hundreds of choices. It's free!
http://www.bigmailbox.com
---------------------------------------------------------------------