Counting

Andy andy.rockford at gmail.com
Sun Apr 29 15:11:04 EDT 2007


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)




More information about the Python-list mailing list