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

Caleb Hattingh caleb1 at telkomsa.net
Thu Nov 25 21:35:00 EST 2004


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




More information about the Python-list mailing list