[Tutor] count words

Magnus Lycka magnus@thinkware.se
Thu Nov 14 15:58:04 2002


text = """Sirs:
I'd like to count the number of times  a letter occurs  in a string.
I've been looking at c. It seems that this type of problem is being
assigned in cs classes on graduate and advanced undergraduate classes in
the US.
Yet, I'm unable to find a library function or simply code written as a
model to help me.
Any pointer in the direction would be greatly appreciated.
I would like to expand this model to include Dolce words, to help
children with reading difficulties.
TIA
Re-v"""

import string

for letter in string.letters:
     print letter, 'occurs', text.count(letter), 'times'

Or, if you don't want to differentiate between upper and
lower case letters:

upperCasedText = text.upper()
for letter in string.uppercase:
     print letter, 'occurs', upperCasedText.count(letter), 'times'

If you read through the library reference thoroughly, I think you
will find lots of goodies. David Beazley's "Python Essential
Reference" is another good presentation of the Python Standard
Library. There is also Fredrik Lundh's book, but I haven't read
that.

Neither of these are tutorials, but to be a really effective
programmer--in any language--it's importent to know the libraries.
One of the advantages with Python is that the basic language is
so easy to learn that while people struggle with syntax in other
languages, it's usually how to find things in the libraries that
bother new Pythonistas.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se