攝影:產品經理
下廚: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}】這個漢字')