python - 组合变音符号不使用 unicodedata.normalize (PYTHON) 规范化

标签 python unicode replace diacritics

我知道 unicodedata.normalize 将变音符号转换为非变音符号:

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

我的问题是(可以在这个例子中看到):unicodedata 是否有办法将组合的 char 变音符号替换成它们的对应物? (u'œ' 变成 'oe')

如果不是,我假设我将不得不为这些打出一击,但我还不如用所有 uchars 和它们的对应物编译我自己的 dict 并完全忘记 unicodedata ...

最佳答案

您的问题中的术语有点困惑。 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 中没有那么多连字。)

关于python - 组合变音符号不使用 unicodedata.normalize (PYTHON) 规范化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12391348/

相关文章:

python - 无换行输出

python - python包的相对导入问题

python - 如何迭代 Python 3 中的 Unicode 字符?

Java ME 双空格中的字符串替换

python - 访问字典中数组中嵌套的数据

python - 这个 Django 应用教程中的choice_set 是什么?

python - 解析包含 Unicode 字符名称的字符串

regex - 使用正则表达式查找 ü(带有变音符号的 u)

c - 我的代码没有正确地将一个单词替换为另一个单词

jQuery 查找带有类名的 td 并更改文本