New to Python.

Sean Ross sross at connectmail.carleton.ca
Thu Mar 18 00:02:58 EST 2004


"droog" <droog at orange.gov> wrote in message
news:dm5i501ccv5atbe4mc6epn1l406ugufkto at 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







More information about the Python-list mailing list