使用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}")
相关推荐
花酒锄作田5 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪9 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽9 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战10 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋16 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama