網站首頁 編程語言 正文
需求來源
在編寫爬蟲訓練場 項目時,碰到一個隨機頭像的需求,這里用漢字去隨機生成。
模擬的效果如下所示,輸入一組漢字,然后返回一張圖片。
接口地址如下所示:
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)
原文鏈接:https://blog.csdn.net/hihell/article/details/128582632
相關推薦
- 2022-03-20 ubuntu開機自啟動服務設置_Linux
- 2023-10-17 npm ERR! code ELIFECYCLE解決方案,npm犯錯!myweb@1.0.0構建腳本
- 2023-02-25 從迷你todo?命令行入門Rust示例詳解_Rust語言
- 2021-12-24 基于PostgreSQL/openGauss?的分布式數據庫解決方案_PostgreSQL
- 2022-02-13 搞明白this指向,走遍天下都不怕(一)
- 2023-05-31 Hadoop腳本遠程控制中SSH常見問題詳解_服務器其它
- 2022-02-17 uni-app的 tabBar添加陰影
- 2023-05-24 pytorch中retain_graph==True的作用說明_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支