Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace by regular expression to lowercase in python

Tags:

python

regex

I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data

keys = ["cat", "dog", "mouse"]
text = "Cat dog cat cloud miracle DOG MouSE"

had to be converted to

converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)"

Here is my code:

keys = "cat|dog|mouse"
p = re.compile(u'\\b(?iu)(?P<name>(%s))\\b' % keys)
converted_text = re.sub(p, '[\g<name>](\g<name>)', text)

And this works fine, only I can't convert last parameter to lower case. This converts like this:

converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](DOG) [MouSE](MouSE)"

how can i convert the last parameter to lowercase? it seems python can't compile the \L sign.

like image 374
jargalan Avatar asked Apr 15 '10 08:04

jargalan


2 Answers

You can use a function to do the replacing:

pattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE)
def format_term(term):
    return '[%s](%s)' % (term, term.lower())

converted_text = pattern.sub(lambda m: format_term(m.group(0)), text)
like image 119
Ants Aasma Avatar answered Sep 18 '22 15:09

Ants Aasma


no need to use regex

>>> keys = ["cat", "dog", "mouse"]
>>> text = "Cat dog cat cloud miracle DOG MouSE"
>>> for w in text.split():
...     if w.lower() in keys:
...        print "[%s]%s" %(w,w.lower()),
...     else:
...        print w,
...
[Cat]cat [dog]dog [cat]cat cloud miracle [DOG]dog [MouSE]mouse
like image 39
ghostdog74 Avatar answered Sep 21 '22 15:09

ghostdog74