是否有一些 python 工具或软件工具可以让我访问字体中的所有组件和表格?

lif*_*ubh 0 python fonts truetype harfbuzz

我的最终目标是创建一个从glyph_id到的映射unicode_chars。该映射将具有某种顺序,glyph_id --> uni_1, uni_2, uni_3 ...因为单个字形可以映射到许多有序的unicode_characters.

我正在寻找一些工具或库,最好是在 python 中,通过它我可以访问所有元信息,例如字体内部的表格。

此外,我正在寻找一些可靠的来源,通过它我可以了解将多个 Unicode 映射到字形的过程。

我知道像 harfbuzz 这样的工具会在给定的 Unicode 字符串上生成(字形、位置)对。但我不确定它是否会反过来。

感谢您提供所有帮助。

dja*_*ude 5

您可能应该查看fontTools Python 库,其中包含处理字体所需的组件。

你感兴趣的字体表是'cmap'表,你想要的基本上是Unicode映射子表的反向映射(有几种子表可以映射Unicode;如果你不熟悉这个概念,我建议查看OpenType 规范以获取更多信息)。基本上你会得到 Unicode 到字形的映射,然后反过来。

fontTools 实际上有一个很好的功能,它会自动选择“最佳”cmap 子表(它有一个首选 cmap 子表类型的有序列表,并返回您打开的特定字体中第一个可用的)。这是使用该函数的示例:

from fontTools.ttLib import TTFont
from collections import defaultdict

font = TTFont('path/to/fontfile.ttf')
unicode_map = font.getBestCmap()
reverse_unicode_map = defaultdict(list)

for k, v in unicode_map.items():
    reverse_unicode_map[v].append(k)
Run Code Online (Sandbox Code Playgroud)

reverse_unicode_map 现在拥有一个字形(字形名称)到整数代码点列表的映射:

>>> reverse_unicode_map
defaultdict(<class 'list'>, {'.null': [0, 8, 29], 'nonmarkingreturn': [9, 13], 'space': [32], 'exclam': [33], 'quotedbl': [34], 'numbersign': [35], 'dollar': [36], 'percent': [37], 'quotesingle': [39], 'parenleft': [40], 'parenright': [41], 'asterisk': [42], 'plus': [43], 'comma': [44], 'hyphen': [45], 'period': [46], 'slash': [47], 'zero': [48], 'one': [49], 'two': [50], 'three': [51], 'four': [52], 'five': [53]})
Run Code Online (Sandbox Code Playgroud)

您可以看到有 2 个字形“.null”和“nonmarkingreturn”映射到多个 Unicode。

如果您需要将字形名称解析为字形索引,则可以使用该font.getGlyphID()方法(传入字形名称;它将返回相应的整数 ID)。