使用python按拼音归类GBK编码表中的所有汉字

|---------------------------------------------------------------------------------|
| 按拼音归类GBK编码表中的所有汉字,每个拼音对应的第一个汉字前面用左大括号,每一个拼音的最后一个汉字后面用右大括号,并保存到txt文本中,并统计包含了多少汉字 |

安装必要的库

确保安装 pypinyin 库用于拼音转换:

bash 复制代码
pip install pypinyin

代码

bash 复制代码
import collections
import pypinyin
 
# 生成 GBK 编码中的所有汉字
gbk_charset = set()
for high_byte in range(0x81, 0xFF):
    for low_byte in range(0x40, 0xFF):
        try:
            byte_seq = bytes([high_byte, low_byte])
            char = byte_seq.decode('gbk')
            if '\u4e00' <= char <= '\u9fff':  # 判断是否为汉字
                gbk_charset.add(char)
        except UnicodeDecodeError:
            continue
 
# 创建拼音分类字典
pinyin_dict = collections.defaultdict(list)
 
# 将汉字按拼音归类
for char in gbk_charset:
    pinyin_list = pypinyin.pinyin(char, style=pypinyin.NORMAL)
    if pinyin_list:
        pinyin = pinyin_list[0][0].lower()
        pinyin_dict[pinyin].append(char)
 
# 统计汉字数量
total_hanzi_count = sum(len(chars) for chars in pinyin_dict.values())
 
# 按拼音排序并保存到文本文件
sorted_pinyin = sorted(pinyin_dict.keys())
 
with open('gbk_hanzi_sorted_by_pinyin.txt', 'w', encoding='utf-8') as f:
    for pinyin in sorted_pinyin:
        chars = pinyin_dict[pinyin]
        if chars:
            formatted_chars = '{' + ''.join(chars) + '}'
            f.write(f"{pinyin}: {formatted_chars}\n")
    f.write(f"\n总共包含的汉字数量: {total_hanzi_count}\n")
 
print("汉字按拼音归类并保存到文本文件完成。")
print(f"总共包含的汉字数量: {total_hanzi_count}")
相关推荐
梦想的旅途211 小时前
企业微信API实战:Python自动化消息推送
java·前端·python·自动化·企业微信
月光船幽幽11 小时前
昆仑流形多模态融合新架构
人工智能·python
爱敲代码的憨仔11 小时前
BM25全文检索
开发语言·python·全文检索
SamChan9011 小时前
用Python+Requests批量翻译PDF:从脚本到调度
后端·python·microsoft·ai·pdf·机器翻译
草莓熊Lotso11 小时前
【LangChain】核心技术:嵌入模型与向量存储完全指南
服务器·网络·python·langchain
leisoo809719 小时前
100GBA股股票数据怎么存ClickHouseRedisMySQLJSON完整对比
大数据·linux·服务器·开发语言·python
WangYan202219 小时前
基于XGBoost与AI的生态—地学多源数据建模:植被与土地利用识别、土壤碳氮空间预测、生物多样性驱动机制、土壤微生物功能预测、生态退化与风险识别
python·机器学习·xgboost
金銀銅鐵1 天前
[Python] 借助 turtle 逐字展示唐诗《金缕衣》
python
Python大数据分析@1 天前
使用大模型MCP采集数据,爬虫已经无门槛
python·网络爬虫
quantdash_cc1 天前
告别自建 Requests/BS4 网页爬虫:基于 QuantDash 搭建零维保的高性能量化行情流水线
开发语言·爬虫·python·pandas·量化·quantdash