一個用於遍歷並檢視ttf字型檔案內所含unicode的python指令碼

用户名还没想好發表於2024-05-17

import os

from fontTools.ttLib import TTFont
import json


def toUnicode(oneStr):
    t = oneStr
    if t[:3] == 'uni':
        t = t.replace('uni', '\\u')
    if t[:2] == 'uF':
        t = t.replace('uF', '\\u')
    t.replace('\\','\\\\')
    return json.loads(f'"{t}"')

def has(ttf,ch):
    glyph_name = None
    for table in ttf['cmap'].tables:
        glyph_name = table.cmap.get(ord(ch))
        if glyph_name is not None:
            break
    if glyph_name is not None:
        glyf = ttf['glyf']
        found = glyf.has_key(glyph_name) and glyf[glyph_name].numberOfContours > 0
    else:
        found = False
    return found

def printUNI(fontName):
    ttf = TTFont(fontName)
    # uniMap = ttf['cmap'].tables[0].ttFont.getBestCmap().values()
    glyphNames = ttf.getGlyphNames()
    for i in glyphNames:
        if i[0] == '.':  # 跳過'.notdef', '.null'
            continue
        if not str(i).startswith('uni'):
            continue
        if str(i).endswith('vert'):
            continue
        if str(i)=='union':
            continue
        if not has(ttf,toUnicode(i)):
            continue
        print(i, toUnicode(i))
        # print(i)



printUNI("./font/1.ttf")

相關文章