【问题标题】:Combined diacritics do not normalize with unicodedata.normalize (PYTHON)组合变音符号不能用 unicodedata.normalize (PYTHON) 规范化
【发布时间】:2012-09-12 15:13:11
【问题描述】:

我了解unicodedata.normalize 将变音符号转换为非变音符号:

import unicodedata
''.join( c for c in unicodedata.normalize('NFD', u'B\u0153uf') 
            if unicodedata.category(c) != 'Mn'
       )

我的问题是(并且可以在此示例中看到):unicodedata 是否有办法将组合的字符变音符号替换为对应的字符? (u'œ' 变成 'oe')

如果不是,我认为我将不得不对这些进行打击,但我不妨用所有 uchars 及其对应物编译我自己的 dict,完全忘记 unicodedata...

【问题讨论】:

    标签: python unicode replace diacritics


    【解决方案1】:

    您的问题中的术语有些混乱。 diacritic 是可以添加到字母或其他字符的标记,但通常不会独立存在。 (Unicode 也使用更通用的术语组合字符。)normalize('NFD', ...) 所做的是将precomposed characters 转换为它们的组件。

    不管怎样,答案是——不是一个预先组合的字符。这是typographic ligature

    >>> unicodedata.name(u'\u0153')
    'LATIN SMALL LIGATURE OE'
    

    unicodedata 模块没有提供将连字拆分成各个部分的方法。但是数据在角色名称中:

    import re
    import unicodedata
    
    _ligature_re = re.compile(r'LATIN (?:(CAPITAL)|SMALL) LIGATURE ([A-Z]{2,})')
    
    def split_ligatures(s):
        """
        Split the ligatures in `s` into their component letters. 
        """
        def untie(l):
            m = _ligature_re.match(unicodedata.name(l))
            if not m: return l
            elif m.group(1): return m.group(2)
            else: return m.group(2).lower()
        return ''.join(untie(l) for l in s)
    
    >>> split_ligatures(u'B\u0153uf \u0132sselmeer \uFB00otogra\uFB00')
    u'Boeuf IJsselmeer ffotograff'
    

    (当然在实践中你不会这样做:你会按照你在问题中的建议预处理 Unicode 数据库以生成查找表。Unicode 中没有那么多连字。)

    【讨论】:

    • 警告:基于包含“LIGATURE”的 Unicode 名称的方法并不可靠。似乎某些连字的名称字符串中没有“LIGATURE”。例如,unicodedata.name(u'\xc6') -> 'LATIN CAPITAL LETTER AE'。
    • 还有 ß (U+00DF),称为“LATIN SMALL LETTER SHARP S”,但可以认为是双 S 连字。
    • @ScottH:你想让我删除这个答案吗?
    • @GarethRees:保留你的答案,这很有用。据我统计,unicodedata 有超过 500 个名称中带有连字的代码点(基于ftp.unicode.org/Public/5.2.0/ucd/NamesList.txt),尽管其中许多是针对其他语言的。我刚刚提到了我的警告,让人们知道存在一些极端情况。
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2011-03-29
    • 2019-07-13
    • 2014-08-24
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多