String Problem
Mike Callahan
mcalla at home.com
Mon May 14 17:24:30 EDT 2001
How about this at first hack:
>>> def func(input, targets, x):
inputlist = input.split(' ')
try:
i = inputlist.index(targets[0])
j = inputlist.index(targets[1])
except ValueError:
return None
if i > j:
i,j = j,i
return ' '.join(inputlist[i-x:j+x+1])
>>> input = "what light through yonder window breaks, tis in the East and
Juliet is the sun"
>>> targets = ('East','yonder')
>>> print func(input, targets, 2)
light through yonder window breaks, tis in the East and Juliet
>>> print func(input, ('light','tis'), 1)
what light through yonder window breaks, tis in
>>>
I am not sure that 10 lines is a mess of code. Of course, you could shorten
it.
Mike
"Colin Meeks" <colinmeeks at home.com> wrote in message
news:s5XL6.93670$2_.31065520 at news3.rdc1.on.home.com...
> 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.?
>
> Colin
>
>
More information about the Python-list
mailing list