Python outputs Chinese character font and converts text into images

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.