一日一技:如何判断某个汉字是否是在字体库中

一日一技:如何判断某个汉字是否是在字体库中

一日一技:如何判断某个汉字是否是在字体库中

摄影:产品经理
下厨:kingname
咱们喜欢从网上下载各类各样的中文字体,但这些字体通常只设计了经常使用汉字,遇到生僻字时就会变成系统默认字体。以下图所示为方正静蕾简体,没有“龍鑨”两个汉字:
一日一技:如何判断某个汉字是否是在字体库中python

如今,我手上有10000个汉字,我如何快速肯定哪些汉字在这个字体库中呢?ide

为了解决这个问题,咱们须要安装 Python 的一个第三方库:fontTools字体

首先咱们来安装它:设计

python3 -m pip install fonttools

而后,咱们编写代码,读取字体库中的全部字体:3d

from fontTools.ttLib import TTFont

font = TTFont('方正静蕾体.ttf')
unicode_map = font['cmap'].tables[0].ttFont.getBestCmap()

这段代码获取的 unicode_map是一个字典,字典的 key 是这个字体库中全部字符的 unicode 码。因此,若是咱们要检查某个汉字在不在这个字体库中,只须要检查汉字的 unicode 码在不在unicode_map中便可:code

words = '一二龍三四'
for word in words:
    if ord(word) in unicode_map:
        print(f'字体库中有:【{word}】这个汉字')
    else:
        print(f'字体库没有:【{word}】这个汉字')

运行效果以下图所示:
一日一技:如何判断某个汉字是否是在字体库中blog

对于守规矩的字体,这样写就足够了。可是有一些字体,他们明明没有某个汉字,却非要把这个汉字的 unicode 码添加到 unicode_map中,因此咱们还能够再进一步检验:ip

glyf_map = font['glyf']
if len(glyf_map[unicode_map[ord(word)]].getCoordinates(0)[0]) == 0:
            print(f'字符:【{word}】确实不在字体库中')

完整的代码以下图所示:unicode

from fontTools.ttLib import TTFont

font = TTFont('方正静蕾体.ttf')
unicode_map = font['cmap'].tables[0].ttFont.getBestCmap()
glyf_map = font['glyf']
words = '一二龍三四'
for word in words:
    if ord(word) in unicode_map and len(glyf_map[unicode_map[ord(word)]].getCoordinates(0)[0]) > 0:
        print(f'字体库中有:【{word}】这个汉字')
        continue
    print(f'字体库没有:【{word}】这个汉字')

一日一技:如何判断某个汉字是否是在字体库中

相关文章
相关标签/搜索