Counting

castironpi at gmail.com castironpi at gmail.com
Sun Apr 29 22:24:44 CEST 2007


On Apr 29, 2:11 pm, Andy <andy.rockf... at gmail.com> 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)

>     tempwords = line.split()
>     for k in tempwords:
           linec = 0
>         if keyword.iskeyword(k):
>             total = total + numwords(k)
>             j = i + 1
               linec += 1
>             print" The word * %s * belongs in line number: %d" % (k,
> j)
           print "%i characters in line" % linec

And less readably,

>     tempwords = line.split()
>     for k in tempwords:
           linec = j
>         if keyword.iskeyword(k):
>             total = total + numwords(k)
>             j = i + 1
>             print" The word * %s * belongs in line number: %d" % (k,
> j)
           print "%i characters in line" % ( j - linec )




More information about the Python-list mailing list