473,698 Members | 2,869 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("Ente r 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(linel ist)):
line = linelist[i]
tempwords = line.split()
for k in tempwords:
if keyword.iskeywo rd(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 1488
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("Ente r 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(linel ist)):
line = linelist[i]
tempwords = line.split()
for k in tempwords:
if keyword.iskeywo rd(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(linel ist):
for k in line.split():
if keyword.iskeywo rd(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("Ente r 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(linel ist)):
line = linelist[i]
tempwords = line.split()
for k in tempwords:
if keyword.iskeywo rd(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(linel ist):
for k in line.split():
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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("Ente r 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(linel ist)):
line = linelist[i]
tempwords = line.split()
for k in tempwords:
if keyword.iskeywo rd(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(linel ist):
for k in line.split():
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
for k in line.split():
if keyword.iskeywo rd(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("Ente r 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(linel ist)):
line = linelist[i]
tempwords = line.split()
for k in tempwords:
if keyword.iskeywo rd(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.iskeywo rd(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.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
line = line.split()
for k in line:
if keyword.iskeywo rd(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(linel ist):
c = 0
line = line.split()
for k in line:
if keyword.iskeywo rd(k):
c += 1
# Alternatively, replace above 5 lines by
# c = sum(keyword.isk eyword(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

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

Similar topics

6
2180
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 not use garbage collection (as Java does). So if the script runs a loop: for i in range(100): f = Obj(i)
1
2709
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 client deletes a refernce to it
1
3248
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 collector, such as the one used in Java, maintains a record of whether or not an object is currentlys being used. An unused object is tagged as garbage,
1
1876
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 collector, such as the one used in Java, maintains a record of whether or not an object is currentlys being used. An unused object is tagged as garbage,
18
2936
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 employee knows anything about Access. I've searched Google Groups, and that has been a lot of help, but there are some questions that I just can't find the answer to. I'll try to take it easy on the group after this question. I have one more...
7
2858
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? #define COUNT(num, count) \ do { \ unsigned char *safe ## num ## count = (unsigned char *)(&(num)); \
1
6922
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 with uploaded MS WORD .doc files. Using code like that below: strLine = sr.ReadLine While Not IsNothing(strLine) 'Not eof If Trim(strLine) <> "" Then 'Not blank
4
4195
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) { } double &operator()(int i) { return myX; }
1
2274
by: oec.deepak | last post by:
Hi Cn any one telll me what is Reference counting in C++.
3
1512
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 OF PEOPLE and counting how many people pick coffee tea oj or lemonade. i have the 5th option set as a sentinel, where the program ends. i need help like i said counting the total number of people who participated(person who quits doesn't...
0
8603
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8893
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4366
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2328
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.