By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,649 Members | 2,142 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,649 IT Pros & Developers. It's quick & easy.

New to Python.

P: n/a

Hello!

I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.

Jul 18 '05 #1
Share this Question
Share on Google+
16 Replies


P: n/a
On Thu, 18 Mar 2004 02:53:48 GMT, droog wrote:
I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.


Can you show us code that you've tried that fails to do what you want?

--
\ "I never forget a face, but in your case I'll be glad to make |
`\ an exception." -- Groucho Marx |
_o__) |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #2

P: n/a
In article <sg********************************@4ax.com>,
droog <dr***@orange.gov> wrote:
Hello!

I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.


Well, I'll point you in the right direction.

To open a file, use the "open" function. You can loop through the lines
with something like "for line in file:". Depending on exactly how you
define "word", you might want to look at the split() string method, or
maybe some regular expression matching with the "re" module.

There, that should be enough to get you started with your homework
assignment :-)
Jul 18 '05 #3

P: n/a
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)

On Thu, 18 Mar 2004 02:53:48 GMT, droog <dr***@orange.gov> wrote:

Hello!

I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.


Jul 18 '05 #4

P: n/a
Thanks for helping, and no this is not a homework assignment
I just like python and wanted to learn it on my own.
droog

On Thu, 18 Mar 2004 03:07:05 GMT, droog <dr***@orange.gov> wrote:
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)

On Thu, 18 Mar 2004 02:53:48 GMT, droog <dr***@orange.gov> wrote:

Hello!

I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.


Jul 18 '05 #5

P: n/a
In article <h8********************************@4ax.com>,
droog <dr***@orange.gov> wrote:
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)


I cut-and-pasted the above onto my machine (just changed the pathname to
/usr/share/dict/words). It finds every line in the file! The problem
appears to be that the find() method returns -1 when there's no match,
which tests as True. Other than that, the code seems pretty reasonable.
Jul 18 '05 #6

P: n/a
Thanks Roy!

Could you please show me an alternative and better way of doing it?
tia

On Wed, 17 Mar 2004 22:22:41 -0500, Roy Smith <ro*@panix.com> wrote:
In article <h8********************************@4ax.com>,
droog <dr***@orange.gov> wrote:
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)


I cut-and-pasted the above onto my machine (just changed the pathname to
/usr/share/dict/words). It finds every line in the file! The problem
appears to be that the find() method returns -1 when there's no match,
which tests as True. Other than that, the code seems pretty reasonable.


Jul 18 '05 #7

P: n/a
In article <dm********************************@4ax.com>,
droog <dr***@orange.gov> wrote:
Thanks Roy!

Could you please show me an alternative and better way of doing it?
tia

On Wed, 17 Mar 2004 22:22:41 -0500, Roy Smith <ro*@panix.com> wrote:
In article <h8********************************@4ax.com>,
droog <dr***@orange.gov> wrote:
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)


I cut-and-pasted the above onto my machine (just changed the pathname to
/usr/share/dict/words). It finds every line in the file! The problem
appears to be that the find() method returns -1 when there's no match,
which tests as True. Other than that, the code seems pretty reasonable.


The basic code you've got seems reasonable, other than the find() bug.
Perhaps not the cleanest or most efficient, but reasonable. Try
changing the test to something like "if line.find ('customer') != -1:"
and see what happens.

If you wanted to be faster, I'd look at the "re" (regular expression)
module. You could do something like:

(outside your mail loop)
prog = re.compile ('customer')

then the test inside your loop would be something:
if prog.match (line):

Note: I'm doing this from memory, so I may have messed up the details a
bit. Check out the documentation for the re module. Unfortunately,
it's one of the more complex modules, so the documentation may be a bit
obtuse to somebody just getting into the language.

Now that I think about it, given that you're looking for a constant
string, I'm not even sure using re will be any faster. But try it both
ways and time it to find out!
Jul 18 '05 #8

P: n/a
How 'bout this:

import string

f=open ('Bob.txt','r')

counter = 0

for line in f.readlines():

word = string.split(line)

for x in word:

if x == 'customer':

counter = counter + 1

print 'Found it ' + str(counter)

"droog" <dr***@orange.gov> wrote in message
news:9k********************************@4ax.com...
Thanks for helping, and no this is not a homework assignment
I just like python and wanted to learn it on my own.
droog

On Thu, 18 Mar 2004 03:07:05 GMT, droog <dr***@orange.gov> wrote:
I was looking for the simpliest way of doing it. This is what I tried
to do.

f = open('C:\Python23\Samples\Bob.txt', 'r')
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
if line.find('customer'):
counter = counter + 1
print 'Found it ' + str(counter)

On Thu, 18 Mar 2004 02:53:48 GMT, droog <dr***@orange.gov> wrote:

Hello!

I have just started learning python and encountered a problem.
All I wanted to do, was to open a text file search and count the
number of occurances of a single word and print that count.
Thanks for help.


Jul 18 '05 #9

P: n/a
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-03-18T03:07:05Z, droog <dr***@orange.gov> writes:
if line.find('customer'):


Note that this method, when fixed, will only count the number of lines where
'customer' occurs, regardless of the number of times it can be found on each
line.

A (slightly) more accurate counter would be:
counter += line.count('customer')

- --
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAWSGH5sRg+Y0CpvERArAWAJ96IrqOogdFTqPLdi8wtn kAlq3l2QCgiXfg
HF+aWKda8pQjtx/1tGA0QMo=
=JBnU
-----END PGP SIGNATURE-----
Jul 18 '05 #10

P: n/a
Nobody wrote:
How 'bout this:

import string

f=open ('Bob.txt','r')

counter = 0

for line in f.readlines():

word = string.split(line)

for x in word:

if x == 'customer':

counter = counter + 1

print 'Found it ' + str(counter)

How about this?
How about this?

counter = 0
for line in file('myfile'):
counter += line.split().count('customer')
print 'Found it', counter

or if the file is relatively small:

print 'Found it', file('myfile').read().split().count('customer')

Jul 18 '05 #11

P: n/a

"droog" <dr***@orange.gov> wrote in message
news:dm********************************@4ax.com...
Could you please show me an alternative and better way of doing it?
tia


# if the file is not very large you can slurp and count
source = file('C:\Python23\Samples\Bob.txt')
tally = source.read().count("customer")
source.close()

# otherwise, you can go line by line
source = file('C:\Python23\Samples\Bob.txt')
tally = 0
for line in source:
if "customer" in line:
tally += 1
source.close()

Note: "customer" matches as a substring. It will match "customers" but not
"Customer", that sort of thing. Depending on how you want to count matches,
you may need to do further text processing (like converting the line to
lower case before matching), or use a regular expression for precise
matching (such as not counting "customers", when you only want to count
"customer").

HTH
Sean


Jul 18 '05 #12

P: n/a
"Sean Ross" <sr***@connectmail.carleton.ca> wrote in message
news:m3*********************@news20.bellglobal.com ...
[snip]
# otherwise, you can go line by line
source = file('C:\Python23\Samples\Bob.txt')
tally = 0
for line in source:
if "customer" in line:
tally += 1
source.close()

[snip]

# sorry, that should be
source = file('C:\Python23\Samples\Bob.txt')
tally = 0
for line in source:
tally += line.count("customer")
source.close()


Jul 18 '05 #13

P: n/a
Sean Ross wrote:
# sorry, that should be
source = file('C:\Python23\Samples\Bob.txt')


You really want to use double backslashes (\\) here or use a raw string
(r'...'). If not, this will eventually bite you.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Pick the roses from the thorns / Wash with waters of the storms
-- Chante Moore
Jul 18 '05 #14

P: n/a

"Erik Max Francis" <ma*@alcyone.com> wrote in message
news:40***************@alcyone.com...
Sean Ross wrote:
# sorry, that should be
source = file('C:\Python23\Samples\Bob.txt')


You really want to use double backslashes (\\) here or use a raw string
(r'...'). If not, this will eventually bite you.


Or forward slashes (/), which avoids the whole problem.

tjr


Jul 18 '05 #15

P: n/a
"Terry Reedy" <tj*****@udel.edu> wrote in
news:ma************************************@python .org:
You really want to use double backslashes (\\) here or use a raw
string (r'...'). If not, this will eventually bite you.


Or forward slashes (/), which avoids the whole problem.


for file() and similar, forward slashes are great, but try to spawn()
something and a raw string works better.

SDF
Jul 18 '05 #16

P: n/a
Scott F wrote:
"Terry Reedy" <tj*****@udel.edu> wrote in
news:ma************************************@python .org:
You really want to use double backslashes (\\) here or use a raw
string (r'...'). If not, this will eventually bite you.


Or forward slashes (/), which avoids the whole problem.


for file() and similar, forward slashes are great, but try to spawn()
something and a raw string works better.


The basic rule is that if you are passing the path through the command
line (in effect, using os.system or spawn and friends), you need to use
backslashes, but any other time forward slashes should be fine.

Unfortunately, if you ever get into comparing path strings, and some
have been made with forward slashes, while others used backslashes or
were run through things like os.path.normpath(), then you'll also get
into trouble.

-Peter
Jul 18 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.