当前位置:主页 > python教程 > Python随机生成汉字

Python实现随机生成一个汉字的方法分享

发布:2023-03-02 19:00:01 59


给大家整理了相关的编程文章,网友苏双玉根据主题投稿了本篇教程内容,涉及到Python随机生成汉字、Python 生成汉字、Python 汉字、Python随机生成汉字相关内容,已被869网友关注,如果对知识点想更进一步了解可以在下方电子资料中获取。

Python随机生成汉字

需求来源

在编写爬虫训练场 项目时,碰到一个随机头像的需求,这里用汉字去随机生成。

模拟的效果如下所示,输入一组汉字,然后返回一张图片。

接口地址如下所示:

https://ui-avatars.com/api/?name=梦想橡皮擦&background=03a9f4&color=ffffff&rounded=true

其中参数说明如下:

  • name:待生成的文字内容;
  • background:背景色;
  • color:前景色;
  • rounded:是否圆形。

我们在下一篇博客完成生成图片效果,本篇先实现随机汉字生成。

随机汉字

生成随机汉字的模块不是 Python 自带的功能,但是你可以使用 Python 的 random 模块来生成随机数,然后使用 Unicode 编码来获取对应的汉字。

下面是一个简单的例子,它生成一个随机的汉字:

import random

def get_random_char():
    # 汉字编码的范围是0x4e00 ~ 0x9fa5
    val = random.randint(0x4e00, 0x9fa5)
    # 转换为Unicode编码
    return chr(val)

print(get_random_char())

如果你想生成多个随机汉字,可以使用一个循环来调用 get_random_char() 函数,并将生成的汉字拼接起来。

下面的代码生成了 5 个随机汉字:

import random

def get_random_char():
    # 汉字编码的范围是0x4e00 ~ 0x9fa5
    val = random.randint(0x4e00, 0x9fa5)
    # 转换为Unicode编码
    return chr(val)

# 生成5个随机汉字
random_chars = ""
for i in range(5):
    random_chars += get_random_char()

print(random_chars)

随机生成常用汉字

直接使用 Unicode 编码,会出现很生僻字,在实战中可以使用部分策略解决该问题,例如找一篇长文,将其存储到一个文本文件中,然后使用 Python 的读写文件功能来读取文件中的汉字。

从互联网找一段文字,添加到 demo.txt 中,用于后续生成随机汉字。

从 demo.txt 中读取文字,这里再补充一个步骤,由于随机生成的文本中会有标点符号,所以需要进行去除。使用 Python 的字符串方法 translate 来实现。

import string

s = "Hello, xiangpica! How are you today?"

# 创建字符映射表
translator = str.maketrans('', '', string.punctuation)

# 使用字符映射表去除标点符号
s = s.translate(translator)

print(s)

结果该方法仅能去除 ASCII 编码的标点符号(例如 !、? 等)。如果去除 Unicode 编码的标点符号,还需要切换方法。

最终选定的模块是 Python 的 unicodedata 模块,其提供了一系列的函数,可以帮助你处理 Unicode 字符的相关信息。

下面是一些常用的 unicodedata 函数:

import unicodedata

print(unicodedata.name('X'))
print(unicodedata.name('0'))
print(unicodedata.name('@'))

unicodedata.lookup(name):返回给定名称的 Unicode 字符。

import unicodedata

print(unicodedata.lookup('LATIN CAPITAL LETTER X'))    # X
print(unicodedata.lookup('DIGIT ZERO'))    # 0
print(unicodedata.lookup('COMMERCIAL AT'))    # @

可以使用 unicodedata.category() 函数来判断一个字符是否是标点符号,然后再使用 translate() 函数来去除标点符号。

下面这段代码,就是使用了 unicodedata 模块和 translate() 函数来去除一段文本中的所有标点符号:

import unicodedata

s = "Hello, xiangpica! How are you today?"

# 创建字符映射表
translator = {ord(c): None for c in s if unicodedata.category(c).startswith('P')}

# 使用字符映射表去除标点符号
s = s.translate(translator)
print(s)

将上述代码集成到 Python 随机生成汉字中,示例如下。

import random
import unicodedata

def get_random_common_char():
    # 读取文件中的常用汉字
    with open('demo.txt', 'r',encoding='utf-8') as f:
        common_chars = f.read()
        # 去除空格
        common_chars = common_chars.replace(' ','')
        common_chars = common_chars.strip()

        # 创建字符映射表
        translator = {ord(c): None for c in common_chars if unicodedata.category(c).startswith('P')}

        # 使用字符映射表去除标点符号
        s = common_chars.translate(translator)


    return random.choice(s)

print(get_random_common_char())

随机生成五个汉字

random_chars = ""
for i in range(5):
    random_chars += get_random_common_char()
print(random_chars)

到此这篇关于Python实现随机生成一个汉字的方法分享的文章就介绍到这了,更多相关Python随机生成汉字内容请搜索码农之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持码农之家!


参考资料

相关文章

网友讨论