[Tutor] partial string matching in list comprehension?

Bob Gailer bgailer at alum.rpi.edu
Fri May 26 00:16:33 CEST 2006


doug shawhan wrote:
> I have a series of lists to compare with a list of exclusionary terms.
>
>
>
> junkList =["interchange",  "ifferen", "thru"]
>
> The comparison lists have one or more elements, which may or may not 
> contain the junkList elements somewhere within:
>
> l = ["My skull hurts", "Drive the thruway", "Interchangability is not 
> my forte"]
>
> ... output would be
>
> ["My skull hurts"]
>
> I have used list comprehension to match complete elements, how can I 
> do a partial match?
>
> def removeJunk(reply, junkList):
>         return [x for x in reply if x not in junkList]
>
> It would be so much prettier than searching through each list element 
> for each term - I tend to get lost in a maze of twisty corridors, all 
> alike.
Just say the magic word PLUGH! Be sure to pick up the batteries while 
you're in there.

How about re?

import re

Build the search pattern:
pattern = "|".join(junkList)

Compile it:
junkListPattern = re.compile(pattern)

def removeJunk(reply, junkListPattern):
        return [x for x in reply if not junkListPattern.search(x)]

*just with your <bare> hands*

-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list