如何在Python中将封闭型字母数字字符转换为普通形式
在Python中转换封闭型字母数字字符并保留带重音字符
要实现将🅰、①、Ⓐ这类封闭型字母数字字符转换为普通形式,同时保留ç、á这类带重音字符,且无需手动构建映射字典,可以借助unidecode库结合Unicode范围判断来完成,具体实现如下:
步骤1:安装依赖库
首先需要安装unidecode库,用于将特殊Unicode字符转换为对应的普通字符:
pip install unidecode
步骤2:实现转换代码
以下代码会对指定字符进行判断:如果属于封闭型字母数字或相关特殊范围,就通过unidecode解码后保留单词字符;否则直接保留原字符(包括带重音的字符):
import re from unidecode import unidecode def convert_enclosed_chars(criteria): return "".join( re.sub(r'([^\w])', '', unidecode.unidecode(ch)) if ( ord(ch) > 65535 # 处理表情类封闭字符 or (ord(ch) >= 9312 and ord(ch) <= 9472) # 圈形字母数字 or (ord(ch) >= 65296 and ord(ch) <= 65305) # 全角数字 or (ord(ch) >= 65313 and ord(ch) <= 65338) # 全角大写字母 or (ord(ch) >= 65345 and ord(ch) <= 65370) # 全角小写字母 ) else ch for ch in criteria )
代码逻辑说明
- 通过
ord(ch)判断字符的Unicode范围,精准定位各类封闭型字母数字; - 用
unidecode将特殊字符转换为普通形式后,通过正则过滤掉封闭框残留的非单词字符; - 不属于目标范围的字符(如带重音的ç、á)直接返回原字符,确保保留其原有格式。
使用示例
test_str = "🅰 ① Ⓐ ç á" result = convert_enclosed_chars(test_str) print(result) # 输出: A 1 A ç á
内容的提问来源于stack exchange,提问作者Quixotic22
相关产品推荐
相关产品推荐

