473,394 Members | 1,831 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 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 1464
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.