Counting

James Stroud jstroud at mbi.ucla.edu
Sun Apr 29 17:17:08 EDT 2007


rockmode at gmail.com wrote:
> That's a short, abridged version of my code :) But, what I want is to
> count total# of keywords per line and print 'em. Rather than
> printing :
> 
> The word 'and' belongs in line num: 1
> The word 'del' belongs in line num: 1
> The word 'from' belongs in line num: 1
> 
> I want to print " Line #1 has 3 keywords"
> 
> ;)
> 


I think it would be obvious how to write this:


for i,line in enumerate(linelist):
   line = line.split()
   for k in line:
     if keyword.iskeyword(k):
       c = line.count(k)
       total += line.count(k)
       print "Line #%d has %d keywords." % (i+1, c)
       break

print "Total keyords are: %d" % total



More information about the Python-list mailing list