String Problem

William Park parkw at
Mon May 14 23:27:18 CEST 2001

On Mon, May 14, 2001 at 08:19:36PM +0000, Colin Meeks wrote:
> I have the following problem and was wondering how people would go
> about solving it.
> I have a variable string with different keywords in it.  What I would
> like to do is trim the string so that it has X words either side of
> the requested keywords.
> i.e. what light through yonder window breaks, tis in the East and
> Juliet is the sun.
> I would like to specify say, Yonder and East and trim the trim to x
> words around it.  So if I wanted 2 words either side I would end up
> with
> "light through yonder window breaks, tis in the East and Juliet"
> I'm trying to write a small search engine.  Although I could write a
> mass of code to do what I want, I was wondering if a regular
> expression could be used, or anything else, similarly simplistic.?

1. Split the string using 'yonder|East':
    >>> re.split('(yonder|East)', s)
    ['what light through ', 'yonder', ' window breaks, tis in the ',
    'East', ' and Juliet is the sun.']

2. Locate 'younder' or 'East', and split the strings before/after using

3. Pick off your 2 words around 'younder' or 'East'.

--William Park, Open Geometry Consulting, Mississauga, Ontario, Canada.
  8 CPU cluster, (Slackware) Linux, Python, LaTeX, vim, mutt

More information about the Python-list mailing list