Python和字符规范化

Hel*_*nar 16 python django utf-8 diacritics transliteration

您好我从外国来源检索基于文本的utf8数据,其中包含特殊字符,例如u"?öüç"我想将它们标准化为英语,例如"?öüç"- > "iouc".实现这一目标的最佳方法是什么?

Con*_*tin 36

我建议使用Unidecode模块:

>>> from unidecode import unidecode
>>> unidecode(u'?öüç')
'iouc'
Run Code Online (Sandbox Code Playgroud)

请注意如何为其提供unicode字符串,并输出一个字节字符串.输出保证为ASCII.


Gar*_*ees 5

这一切都取决于你想要在多大程度上音译结果.如果你想将所有内容一直转换为ASCII(???to abg),那么unidecode就是要走的路.

如果你只是想从重音字母中删除重音,那么你可以尝试使用标准化形式NFKD来分解你的字符串(这会将带重音的字母转换为后跟á的普通字母),然后丢弃重音符号(属于Unicode字符类 - "马克,非间距").aU+0301 COMBINING ACUTE ACCENT Mn

import unicodedata

def remove_nonspacing_marks(s):
    "Decompose the unicode string s and remove non-spacing marks."
    return ''.join(c for c in unicodedata.normalize('NFKD', s)
                   if unicodedata.category(c) != 'Mn')
Run Code Online (Sandbox Code Playgroud)