removing accent and special characters [duplicate]

爷,独闯天下 提交于 2019-12-29 04:47:25

问题


Possible Duplicate:
What is the best way to remove accents in a python unicode string?
Python and character normalization

I would like to remove accents, turn all characters to lowercase, and delete any numbers and special characters.

Example :

Frédér8ic@ --> frederic

Proposal:

def remove_accents(data):
    return ''.join(x for x in unicodedata.normalize('NFKD', data) if \
    unicodedata.category(x)[0] == 'L').lower()

Is there any better way to do this?


回答1:


A possible solution would be

def remove_accents(data):
    return ''.join(x for x in unicodedata.normalize('NFKD', data) if x in string.printable).lower()

Using NFKD AFAIK is the standard way to normalize unicode to convert it to compatible characters. The rest as to remove the special characters numbers and unicode characters that originated from normalization, you can simply compare with string.ascii_letters and remove any character's not in that set.




回答2:


Can you convert the string into HTML entities? If so, you can then use a simple regular expression.

The following replacement would work in PHP/PCRE (see my other answer for an example):

'~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i' => '$1'

Then simply convert back from HTML entities and remove any non a-Z char (demo @ CodePad).

Sorry I don't know Python enough to provide a Pythonic answer.



来源:https://stackoverflow.com/questions/8694815/removing-accent-and-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!