欢迎访问宙启技术站
智能推送

使用matplotlib中的FontProperties()在Python中生成随机中文标题

发布时间:2024-01-09 08:46:52

import matplotlib.pyplot as plt

import random

from matplotlib.font_manager import FontProperties

# 设置中文字体

font = FontProperties(fname='SimHei.ttf', size=16)

# 随机生成中文标题

def generate_chinese_title():

    title_length = random.randint(1, 10)  # 标题长度为1-10个字

    title = ''

    for _ in range(title_length):

        # Unicode编码范围:4E00-9FFF是常用汉字的范围

        code = random.randint(0x4E00, 0x9FFF)

        char = chr(code)

        title += char

    return title

# 生成1000个随机中文标题

titles = []

for _ in range(1000):

    titles.append(generate_chinese_title())

# 绘制标题长度分布图

title_lengths = [len(title) for title in titles]

plt.hist(title_lengths, bins=range(1, 11), edgecolor='black')

plt.xlabel('标题长度', fontproperties=font)

plt.ylabel('频数', fontproperties=font)

plt.title('随机中文标题长度分布图', fontproperties=font)

plt.show()