Counting

James Stroud jstroud at mbi.ucla.edu
Sun Apr 29 16:13:50 EDT 2007


James Stroud wrote:
> Andy wrote:
>> Hi, the file below will print all the keywords in a file and also the
>> line # of the keyword. What I couldn't figure out is to count those
>> keywords per line. For example - "Line #1 has 3 keywords"
>>
>> Can I do like -
>>
>> total[j] = total[j] + numwords(k)
>> "Line number %d has %d keywords" % (j, total[j])
>>
>> Seems sort of "illegal" in Python?
>>
>>
>>
>> -------------------------------------------------
>> import keyword, sys, string, fileinput
>> def numwords(s):
>>     list = string.split(s)
>>     return len(list)
>>
>> # Get the file name either from the command-line or the user
>> if len(sys.argv) != 2:
>>    name = raw_input("Enter the file name: ")
>> else:
>>    name = sys.argv[1]
>>
>> inp = open(name,"r")
>> linelist = inp.readlines()
>> total, words,lines = 0, 0, 0
>>
>> for i in range(len(linelist)):
>>     line = linelist[i]
>>     tempwords = line.split()
>>     for k in tempwords:
>>         if keyword.iskeyword(k):
>>             total = total + numwords(k)
>>             j = i + 1
>>             print" The word * %s * belongs in line number: %d" % (k,
>> j)
>>
>> print "Total keywords in this file are: %d" %(total)
>>
> 
> You probably want something that goes a little like this:
> 
> for i,line in enumerate(linelist):
>   for k in line.split():
>     if keyword.iskeyword(k):
>       total += line.count(k)
>       print "The word '%s' belongs in line num: %d" % (k, i+1)
> 
> print "Total keyords are: %d" % total
> 
> James

Oops, that over-counts, I forgot to put a continue in. Also, keeping a 
cache of the split line will probably be faster.

for i,line in enumerate(linelist):
   line = line.split()
   for k in line:
     if keyword.iskeyword(k):
       total += line.count(k)
       print "The word '%s' belongs in line num: %d" % (k, i+1)
       continue

print "Total keyords are: %d" % total


James



More information about the Python-list mailing list