将变音符号或修饰变音符号 Unicode 字符转换为“组合形式”

Nol*_*rin 5 python unicode text

我在 Unicode 字符串中有一些重音/变音符号,我想将它们转换成它们的“组合形式”(根据 Unicode 标准)。例如,如果我有\N{CIRCUMFLEX ACCENT}( \u005E) 或\N{MODIFIER LETTER CIRCUMFLEX ACCENT}( \u02C6),我想将其转换为\N{COMBINING CIRCUMFLEX ACCENT}( \u0302)。对于任何变音符号,是否有一致、可靠的方法来执行此操作?如果 Python (3.9) 标准库对其有内置支持(可能通过unicodedata模块),那将是理想的选择,但我也很高兴为此使用 pip 包。

Nol*_*rin 2

这是我目前最好的解决方案。感觉还是有点老套,但它似乎适用于我遇到的场景。

from typing import *
import unicodedata

def _strip_prefix(s: str, prefix: str) -> str:
    return s[len(prefix):] if s.startswith(prefix) else s

def make_combining_form(diacritic: str) -> Optional[str]:
    if unicodedata.category(diacritic) not in ("Sk", "Lm"):
        return None

    name = unicodedata.name(diacritic)
    name = _strip_prefix(name, "MODIFIER LETTER ")
    name = _strip_prefix(name, "COMBINING ")
    try:
        return unicodedata.lookup("COMBINING " + name)
    except KeyError:
        return None
Run Code Online (Sandbox Code Playgroud)