Python输出汉字字库及将文字转换为图片的方法

yipeiwu_com6年前Python基础

用python输出汉字字库
问题1:假设我们知道汉字编码范围是0x4E00到0x9FA5,怎么从十六进制的编码转成人类可读的字呢?
问题2:怎么把unicode编码的字写入文件呢,如果直接用open()的话,会提示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文件,截图如下

201664103455668.png (552×171)

用python将文本转图片字库
上面提到怎么得到汉字字库,下面就来讲怎么把一个一个的字转成图片,这在机器学习中会有用处。
一句话,用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)#当前目录下要有微软雅黑的字体文件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")) 

下面是效果截图。

201664103526744.png (720×246)

相关文章

Python二叉树的定义及常用遍历算法分析

本文实例讲述了Python二叉树的定义及常用遍历算法。分享给大家供大家参考,具体如下: 说起二叉树的遍历,大学里讲的是递归算法,大多数人首先想到也是递归算法。但作为一个有理想有追求的程序...

pytorch 数据处理:定义自己的数据集合实例

数据处理 版本1 #数据处理 import os import torch from torch.utils import data from PIL import Image im...

python base64 decode incorrect padding错误解决方法

python的base64.decodestring方法做base64解码时报错: 复制代码 代码如下: Traceback (most recent call last):  ...

Pandas库之DataFrame使用的学习笔记

Pandas库之DataFrame使用的学习笔记

1 简介 DataFrame是Python中Pandas库中的一种数据结构,它类似excel,是一种二维表。 或许说它可能有点像matlab的矩阵,但是matlab的矩阵只能放数值型值(...

机器学习经典算法-logistic回归代码详解

机器学习经典算法-logistic回归代码详解

一、算法简要 我们希望有这么一种函数:接受输入然后预测出类别,这样用于分类。这里,用到了数学中的sigmoid函数,sigmoid函数的具体表达式和函数图象如下: 可以较为清楚的看到,...