[Tutor] Re: Capitalization what does it do exactly

Magnus Lycka magnus@thinkware.se
Thu Nov 7 02:32:02 2002


At 16:52 2002-11-06 -0800, Danny Yoo wrote:
> >>> def acronym(sentence):
>...     return join([word[0] for word in sentence])
>...
> >>> def join(words):
>...     return "".join(words)
>...
> >>> acronym(["International", "Business", "Machines"])
>'IBM'
> >>> acronym(['I', 'Am', 'Not', 'A', 'Lawyer'])
>'IANAL'
>###
>
>This is a really simple function, perhaps too simple.

Two functions Danny! One too much I think...

>Are there any improvements we can make to something like this to make it
>better or cleaner?

 >>> def acronym(sentence):
...     return "".join([word[0] for word in sentence.split()])
...
 >>> print acronym('Painting your two horses often needed')
Python

Remove the split if you want to start with a list.
What made you wrap such a tiny thing as "".join(words)
in a function on its own?

If you prefer to use regular expressions, you can make
it somewhat shorter (not that it feels important).

import re
def acronym(sentence):
     return "".join(re.findall(r'\b\w',sentence))

Either of these will be confusing if the underlying concept
(list comprehension and regular expressions) is unknown to
you...

Another approach would be to filter out upper case letters.
It all depends on what you want.

 >>> print filter(lambda x: x in string.uppercase,
               "Think before yoU posT OR you'll be sorry!")
TUTOR

Or as a function using filter or list comprehension:

 >>> def getCaps(aString):
...     import string
...     return filter(lambda c: c in string.uppercase, aString)
...
 >>> print getCaps('If I Recall Correctly')
IIRC
 >>> def getCaps(aString):
...     import string
...     return "".join([c for c in aString if c in string.uppercase])
...
 >>> print getCaps('Read The Fine Manual')
RTFM

Of course if you have the getCaps function, you can use that
to get "real" acronyms based on the initials.

 >>> print getCaps(string.capwords('inTerNational buSiness macHines'))
IBM

Does anyone know why there isn't a "asd asd".capwords() method?


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