Remove accents in python

Viewed 27

I'm trying to remove all the accents in a string in python using unidecode

and it work pretty well

import unidecode

print(unidecode.unidecode('ááíãôç'))

it returns

aaioac

The problem is that i need to keep the 'ç' character

aaiaoç

Is there some way or some library i can use ? Instead of hard code my way out of this problem ?

1 Answers

Well, unidecode is meant for stripping diacriticals and other things, so that's what it does.

If you need to keep some, well-known characters as-is, you'll need to partition the string so those characters aren't run through unidecode. (Mapping the characters to e.g. Unicode PUA characters and then back won't do – unidecode gobbles them up.)

A suitable way to do that is to come up with a regexp that matches every other character, then use the re.sub() function's callback mode to run those runs through unidecode:

>>> import unidecode
>>> import re
>>> keep = 'çÇ'
>>> s = 'ááíãôç hållå! höellô!'
>>> re.sub(f"([^{re.escape(keep)}]+)", lambda m: unidecode.unidecode(m.group(0)), s)
'aaiaoç halla! hoello!'
Related