vendredi 23 novembre 2018

List Comprehension with multiple Regex with Python

I am trying to add multiple regular expressions in a single List Comprehension, from what I'd read online it appears to be possible using multiple else statements though I can't seem to get it to work:

def normalise(token):
    print(["NUM" if token.isdigit() 
    else "Nth" if token in "[\d]+(st|nd|rd|th)" 
    else token for token in token])

normalise(["Within","5","minutes",",","the", "1st", "and",
"2nd", "placed", "runners", "lapped", "the", "5th","."])  

What I'm trying to do is change numbers with NUM and tokens representing a place (1st,2nd,3rd etc) to be replaced with Nth. All other tokens are unchanged. The first regex isdigit() works completely fine though I'm unsure of how to insert the second one successfully, it just gets ignored. If it is possible with 2 regex that then means it is possible with as many regex as I wish?

Aucun commentaire:

Enregistrer un commentaire