Replacing words from strings except 'and' / 'or' / 'and not'

Berthold Höllmann bhoel at despammed.com
Thu Nov 25 15:20:56 EST 2004


"Caleb Hattingh" <caleb1 at telkomsa.net> writes:

> Oh well, I might as well give it a shot.  I hope nobody has tried map yet?
>
> This is is short and quick, although:
> I sure would appreciate some help changing the list "lkw" into a
> generator  (or something like that) instead...those fancy things are
> still beyond me  :)
>
> '>>> keywords = ['my','is']
> '>>> sentence = 'hi there my name is caleb'
> '>>> lsen = sentence.split()
> '>>> lkw = []
> # Yuck!  isn't there a better way to generate copies of the same list
> in  the "map" below??
> '>>> for i in range(len(lsen)):
> 	lkw.append(keywords)

Maybe here 

'>>> for i in lsen:
	lkw.append(keywords)

is enough?

> 	
> '>>> lkw
> # Like I said, yuck!  For 'map' below, can't we use a generator or
> something like that instead??
> [['my', 'is'], ['my', 'is'], ['my', 'is'], ['my', 'is'], ['my', 'is'],
> ['my', 'is']]
> '>>> def myfunc(kw,word):
> 	if word in kw:
> 		return '*'+word+'*'
> 	else:
> 		return word
>
> 	
> '>>> ans = map(myfunc,lkw,lsen)
> '>>> ans
> ['hi', 'there', '*my*', 'name', '*is*', 'caleb']
> '>>> newSentence = ' '.join(ans)
> '>>> newSentence
> 'hi there *my* name *is* caleb'
> '>>>
My solution would be:

>>> keywords = ['my','is']
>>> sentence = 'hi there my name is caleb'
>>> lsen = sentence.split()
>>> def myfunc(kw,word):
...     if word in kw:
...         return '*%s*' % word
...     else:
...         return word
... 
>>> ans = [ myfunc(keywords, word) for word in lsen ]
>>> ans
['hi', 'there', '*my*', 'name', '*is*', 'caleb']
>>> newSentence = ' '.join(ans)
>>> newSentence
'hi there *my* name *is* caleb'

Kind Regards
Berthold
-- 
berthold at xn--hllmanns-n4a.de / <http://höllmanns.de/>
bhoel at web.de                 / <http://starship.python.net/crew/bhoel/>



More information about the Python-list mailing list