472,371 Members | 1,657 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

Counting

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)

Apr 29 '07 #1
11 1375
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
Apr 29 '07 #2
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
Apr 29 '07 #3
James Stroud wrote:
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
I should really wait until I've had some coffee. Not continue, but break!
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)
break

print "Total keyords are: %d" % total
Apr 29 '07 #4
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"

;)

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

Apr 29 '07 #5
On Apr 29, 2:11 pm, Andy <andy.rockf...@gmail.comwrote:
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 )

Apr 29 '07 #6
ro******@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
Apr 29 '07 #7
I pretty doubt about this - "c = line.count(k)" I might wanna recheck
on that.
-------------------------------------
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

Apr 30 '07 #8
James -

I pretty doubt about this - "c = line.count(k)" You might wanna
recheck on that.
------------------------------------------------
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

>
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

Apr 30 '07 #9
On 30/04/2007 7:17 AM, James Stroud wrote:
ro******@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
I would have thought so too. But the above is ... let's just say it's
not quite right. If there are 3 different keywords (as in the OP's
example), the above code prints 3 times for the same line.

Here's a straight-forward natural way to do it:
total = 0
for i, line in enumerate(linelist):
c = 0
line = line.split()
for k in line:
if keyword.iskeyword(k):
c += 1
# Alternatively, replace above 5 lines by
# c = sum(keyword.iskeyword(k) for k in line.split())
# or the equivalent using map(), depending on taste etc :-)
total += c
print "Line #%d has %d keywords." % (i+1, c)
print "Total number of keywords is", total

======

Perhaps someone should point out to the OP that using str.split as a
tokeniser is somewhat deficient:
1. comments and string literals could make the counts somewhat unreliable:
"# if not use mung(), will break while frobotzing later in code"
2. "else:"
3. "if not(0 <= n < maxn):"

HTH,
John
Apr 30 '07 #10
James Stroud wrote:
James Stroud wrote:
>James Stroud wrote:
[finally ...]
>
I should really wait until I've had some coffee. Not continue, but break!
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)
break

print "Total keyords are: %d" % total
James is actually trying to convince you of the merits of test-driven
development by cleverly showing you the disadvantages of not using it.

Clever approach to advocacy, James. Did you get your coffee yet?

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------

May 5 '07 #11
..o0

May 7 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Elbert Lev | last post by:
Please correct me if I'm wrong. Python (as I understand) uses reference counting to determine when to delete the object. As soon as the object goes out of the scope it is deleted. Python does...
1
by: ash | last post by:
hi does anyone has any experience with flyweight pattern with refernce counting i want to share objects between multiple clients and want to delete the object from shared pool when the last...
1
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that I don't understand completely. It says "A garbarage...
1
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that I don't understand completely. It says "A garbarage...
18
by: ChadDiesel | last post by:
I appreciate the help on this group. I know I've posted a lot here the last couple of weeks, but I was thrown into a database project at my work with very little Access experience. No other...
7
by: zets | last post by:
I need a macro for counting the bits in the odd positions of a given input (of any type, char, pointer, int, struct, whatever). Is there any clever way I could not think of, to do it efficiently? ...
1
by: j | last post by:
Hi, I've been trying to do line/character counts on documents that are being uploaded. As well as the "counting" I also have to remove certain sections from the file. So, firstly I was working...
4
by: aaronfude | last post by:
Hi, Please consider the following class (it's not really my class, but it's a good example for my question): class Vector { int myN; double *myX; Vector(int n) : myN(n), myX(new double) { }...
1
by: oec.deepak | last post by:
Hi Cn any one telll me what is Reference counting in C++.
3
by: nitric | last post by:
hey guys, i'm really stuck on this program. It's basically a survey and I have to ask people what drinks they like. 1-4, coffee tea oj and lemonade. i'm having trouble counting the TOTAL NUMBER...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.