用python輸出漢字字庫
問題1:假設(shè)我們知道漢字編碼范圍是0x4E00到0x9FA5,怎么從十六進(jìn)制的編碼轉(zhuǎn)成人類可讀的字呢?
問題2:怎么把unicode編碼的字寫入文件呢,如果直接用open()的話,會(huì)提示UnicodeEncodeError: 'ascii' codec can't encode character u'/u4e00' in position 0: ordinal not in range(128)
問題1的答案是用unichr,問題2的答案是用codecs。
下面上代碼。
import codecs start,end = (0x4E00, 0x9FA5) with codecs.open("chinese.txt", "wb", encoding="utf-8") as f: for codepoint in range(int(start),int(end)): f.write(unichr(codepoint)) 打開chinese.txt文件,截圖如下

用python將文本轉(zhuǎn)圖片字庫
上面提到怎么得到漢字字庫,下面就來講怎么把一個(gè)一個(gè)的字轉(zhuǎn)成圖片,這在機(jī)器學(xué)習(xí)中會(huì)有用處。
一句話,用pygame渲染文字到圖片上。
下面上代碼。
import os import pygame chinese_dir = 'chinese' if not os.path.exists(chinese_dir): os.mkdir(chinese_dir) pygame.init() start,end = (0x4E00, 0x9FA5)#漢字編碼范圍 for codepoint in range(int(start),int(end)): word = unichr(codepoint) font = pygame.font.Font("msyh.ttc", 22)#當(dāng)前目錄下要有微軟雅黑的字體文件msyh.ttc,或者去c:/Windows/Fonts目錄下找 rtext = font.render(word, True, (0, 0, 0), (255, 255, 255)) pygame.image.save(rtext, os.path.join(chinese_dir,word+".png")) 下面是效果截圖。

新聞熱點(diǎn)
疑難解答
圖片精選