473,396 Members | 1,998 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,396 software developers and data experts.

New to Python.


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
16 1527
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
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
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
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
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
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
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
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
-----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
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

"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
"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
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

"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
"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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.