使用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}")
相关推荐
卷无止境3 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿4 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户0332126663674 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿5 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
Wellijohn6 小时前
Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行
python
AI创界者6 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc
炸薯条!7 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
tryCbest8 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
VIP_CQCRE8 小时前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
2601_967987378 小时前
使用 NumPy 和 Python 实现梯度下降
python·机器学习·线性回归·numpy·梯度下降