Replacing words from strings except 'and' / 'or' / 'and not'
Jerry Sievers
jerry at jerrysievers.com
Sat Nov 27 11:33:55 EST 2004
Alexandre Cecchi <a.cecchi at gmail.com> writes:
> > Hi there,
> >
> > Background of this question is:
> > I want to convert all words <word> except 'and' / 'or' / 'and not' from
> > a string into '*<word>*'.
>
> Hello,
>
> def do(s):
> L = []
> for x in s.split():
> if x in ('or','and'):
> L.append(x)
> elif x == 'not' and L and L[-1] == 'and':
> L.append('not')
> else:
> L.append("'*%s*'" % x)
> return ' '.join(L)
>
> I think that it is more readable, maybe not faster, elegant I don't know =)
> print 'Yeahh it was my first post on the list.'
>
> bye.
Might as well throw in a recursive approach, eh?
excludedWords = {'foo': 1, 'bar': 1}
def fixEmUp(list, result = []):
x = list.pop(0)
result.append('*' * int(x not in excludedWords) + x)
if not list:
return result
return fixEmUp(list, result)
Takes a list of words and returns the same list with the words not in
excludedWords with the * prepended.
(Original poster's professor is going to ask for this
eventually... :-)
A very easy way might be to use REs with negative look-ahead on the
excluded words.
Peace
--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
More information about the Python-list
mailing list