[Tutor] Hi All

Joe recumbentjoe@zianet.com
25 Aug 2002 12:13:42 -0400


#!/usr/bin/python

# Wordcount.py
# Program to count both lines and words in a text file.
# suggested by Joe Richey
# 8/25/02
#

import sys
import string
from string import *

filename=""
filename=raw_input("Enter the filename :")
if len(filename)<1 :
   sys.exit()

#set up int and strings space needed
wordcount=0
linecount=0
totalwords=0
linelist=""
wordlist=""
totallines=0

f=file(filename,"r")   #Open file as needed
linelist=f.readlines()     #Get everything into a list

totallines=len(linelist) #get how many lines in file

print"\nLINE#  WORDS"
print"------------\n\n"
while linecount <= totallines-1:
   wordlist=split(linelist[linecount])
   print"%d      %d words" % (linecount+1,len(wordlist))
   totalwords=totalwords+len(wordlist)
   linecount=linecount+1

print"------------"
print "Summary:"

print "%d lines, %d words, Avg: %d words/line" %(totallines,totalwords,(totalwords/totallines))

I'm also new at Python, but maybe more then one week. The above code seems to work 
ok for me here. Its totally new from yours as I wasn't sure where you were going with
yours. Hope it does not confuse you too much and you will need to work on the Average
routine at the end (i used a int and you wanted a float)

Joe


On Thu, 2002-08-22 at 07:42, Morne wrote:
> Hi could one or 2 of you help me with this I have gotten this far I havnt got the hang of python yet but am working on it .
> 
> Here it goes:
> 
> def getStuff(file)
>      info = open(file,"r")
>      infolines = info.readlines()
>     for line in infolines:
>     word = string.split(lines)
>    print"Line %d contains %d words" % (linenum,len(word))
>    linenum += 1
>    totalwords += len(words)
>     print "Total lines:", linenum - 1
>     print "Average words per line:", float(totalwords)/linenum - 1
> file = raw_input("Enter the filename: ")
> getStuff(file)
> 
> 
> Here is what I want it to do it takes a text file and counts the number of
> lines in the file, the number of words in a line and then produces a
> summary.  The Output must look like this.
> 
> 
> 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
> 
> 
> 
>  
> Can you pease let me know if this is right and if not "what the errors are and how to fix them
> I have until tomorrow and then my boss wants me to show him what I know he has given me 5 days to do this and I used python for the first time on Monday. And I will be asking you all alot more questions.
> 
> Thanx From morne