【问题标题】:Given a list of Unicode code points, how does one split them into a list of Unicode characters?给定一个 Unicode 代码点列表,如何将它们拆分为 Unicode 字符列表?
【发布时间】:2016-06-26 00:02:55
【问题描述】:

我正在为 Unicode 文本编写一个词法分析器。许多 Unicode 字符需要多个代码点(即使在规范组合之后)。例如,tuple(map(ord, unicodedata.normalize('NFC', 'ā́'))) 的计算结果为 (257, 769)。我怎么知道两个字符之间的边界在哪里?此外,我想存储文本的非规范化版本。我的输入保证是 Unicode。

到目前为止,这就是我所拥有的:

from unicodedata import normalize

def split_into_characters(text):
    character = ""
    characters = []

    for i in range(len(text)):
        character += text[i]

        if len(normalize('NFKC', character)) > 1:
            characters.append(character[:-1])
            character = character[-1]

    if len(character) > 0:
        characters.append(character)

    return characters

print(split_into_characters('Puélla in vī́llā vīcī́nā hábitat.'))

这会错误地打印以下内容:

['P', 'u', 'é', 'l', 'l', 'a', ' ', 'i', 'n', ' ', 'v', 'ī', '́', 'l', 'l', 'ā', ' ', 'v', 'ī', 'c', 'ī', '́', 'n', 'ā', ' ', 'h', 'á', 'b', 'i', 't', 'a', 't', '.']

我希望它打印以下内容:

['P', 'u', 'é', 'l', 'l', 'a', ' ', 'i', 'n', ' ', 'v', 'ī́', 'l', 'l', 'ā', ' ', 'v', 'ī', 'c', 'ī́', 'n', 'ā', ' ', 'h', 'á', 'b', 'i', 't', 'a', 't', '.']

【问题讨论】:

    标签: python python-3.x unicode grapheme


    【解决方案1】:

    可以使用 Unicode 的Grapheme Cluster Boundary algorithm 来识别感知字符之间的边界。 Python 的 unicodedata 模块没有算法所需的数据(Grapheme_Cluster_Break 属性),但可以在 PyICUuniseg 等库中找到完整的实现。

    【讨论】:

    • 天哪。两者都有相当宽松的许可证。完美的!谢谢!
    【解决方案2】:

    您可能想要使用pyuegc 库,这是一种Unicode 算法的实现,用于将代码点序列分解为UAX #29 中指定的扩展字形簇

    from pyuegc import EGC  # pip install pyuegc
    
    string = 'Puélla in vī́llā vīcī́nā hábitat.'
    egc = EGC(string)
    print(egc)
    # ['P', 'u', 'é', 'l', 'l', 'a', ' ', 'i', 'n', ' ', 'v', 'ī́', 'l', 'l', 'ā', ' ', 'v', 'ī', 'c', 'ī́', 'n', 'ā', ' ', 'h', 'á', 'b', 'i', 't', 'a', 't', '.']
    
    print(len(string))
    # 35
    print(len(egc))
    # 31
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2020-12-11
      • 2015-09-18
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多