using target words from arrays in regex, pythons version of perls 'map'

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue May 16 02:49:55 EDT 2006


"Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote in message
news:41mi62hih1d3i53nnhdkfi9tpil77bfdp7 at 4ax.com...
> On Mon, 15 May 2006 19:41:39 -0500, Lance Hoffmeyer
> <lance at augustmail.com> declaimed the following in comp.lang.python:
> > I would have something similar to perl above:
> >
> >
> > targets = ['OVERALL RATING',
> >            'CLOTHING', ITEMS',
> >            'ACCESSORIES',
> >            'SHOES',
> >            'FINE JEWELRY']
> >
> > PROPOSED CODE:
> >
> > match2 = re.search(targets[i].*?(?:(\d{1,3}\.\d)\s+){3} ', file2);m[i] =
match2.group(1)
> >
> >
> I don't do regex's, and I also don't find packing multiple statements on
one line attractive.

I concur - this kind of multiple-statements-per-line-ishness feels
gratuitous.  Yes, I know they line up nicely when all 6 statements are
printed out together, but the repetition of "mNN = match2.group(1) ;print
mNN" should tell you that this might be better done with a for loop.  DRY.

>
> However... Why don't you basically do what you say you do in
> Python... Substitute you targets into the expression while inside a
> loop...
>
> targets = [ "OVERALL RATING",
> "CLOTHING",
> "ITEMS",
> "ACCESSORIES",
> "SHOES",
> "FINE JEWELRY" ]
>
> results = []
> for t in target:
> m2 = re.search("%s.*?(?:(\d{1,3}\.\d)\s+){3}" % t, file2)
> results.append(m2.group(1))
> -- 


# by contrast, here is a reasonably Pythonic one-liner, if one-liner it must
be
results = [ re.search(r"%s.*?(?:(\d{1,3}\.\d)\s+){3}" % t, file2).group(1)
for t in targets ]

# or for improved readability (sometimes 2 lines are better than 1):
reSearchFunc = lamdba tt,ff : re.search(tt + r".*?(?:(\d{1,3}\.\d)\s+){3}",
ff).group(1)
results = [ reSearchFunc(t,file2) for t in targets ]


Resisting-the-urge-to-plug-pyparsing-ly yours,
-- Paul





More information about the Python-list mailing list