New to Python.

Roy Smith roy at panix.com
Wed Mar 17 22:37:36 EST 2004


In article <dm5i501ccv5atbe4mc6epn1l406ugufkto at 4ax.com>,
 droog <droog at 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 <roy at panix.com> wrote:
> 
> >In article <h84i501homhvjv6a4ohmf0o4svlakcqtoa at 4ax.com>,
> > droog <droog at 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!



More information about the Python-list mailing list