This article mainly introduces how to output a Chinese character font in Python and convert text into images. codecs and pygame modules are used respectively. For more information, see
Output Chinese character Library in python
Question 1: if we know that the Chinese character encoding range is 0x4E00 to 0x9FA5, how can we convert the hexadecimal code into a human-readable word?
Question 2: How can I write unicode-encoded words into a file? if open () is used directly, the UnicodeEncodeError message is displayed: 'ascii 'codec can't encode character u' \ u4e00' in position 0: ordinal not in range (128)
The answer to question 1 is to use unichr, and the answer to question 2 is to use codecs.
The code below.
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))
Open the chinese.txt file, as shown below:
The code below.
Import OS import pygame chinese_dir = 'China' if not OS. path. exists (chinese_dir): OS. mkdir (chinese_dir) pygame. init () start, end = (0x4E00, 0x9FA5) # Chinese character encoding range: for codepoint in range (int (start), int (end): word = unichr (codepoint) font = pygame. font. font ("msyh. ttc ", 22) # The current directory must contain the font file msyh of. or go to the c: \ Windows \ Fonts directory to find rtext = font. render (word, True, (0, 0, 0), (255,255,255) pygame. image. save (rtext, OS. path. join (chinese_dir, word + ". png "))
The following figure shows the effect.
For more articles about how to output a Chinese character font in Python and convert the text to an image, follow the PHP Chinese website!