pypinyin

2022/4/16 6:42:37

本文主要是介绍pypinyin,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录
  • 汉字编码
  • pypinyin
    • 单字拼音预测有误/远古多音字问题:
    • 通过拼音索引汉字

汉字编码

  • GB2312编码:
    共7445个字符,其中包括6763个汉字(一级汉字3755个,二级汉字3008个)和682个其它字符。
  • Unicode汉字:四字节,基本汉字20902字,编码4E00-9FA5
  • 其他:
    • BIG5编码:台湾地区繁体中文标准字符集,采用双字节编码,共收录13053个中文字,1984年实施。
    • GBK编码:1995年12月发布的汉字编码国家标准,是对GB2312编码的扩充,对汉字采用双字节编码。GBK字符集共收录21003个汉字,包含国家标准GB13000-1中的全部中日韩汉字,和BIG5编码中的所有汉字。
    • GB18030编码:2000年3月17日发布的汉字编码国家标准,是对GBK编码的扩充,覆盖中文、日文、朝鲜语和中国少数民族文字,其中收录27484个汉字。GB18030字符集采用单字节、双字节和四字节三种方式对字符编码。兼容GBK和GB2312字符集。
    • UTF-8和UTF-16编码:Unicode编码的转换格式,可变长编码,相对于Unicode更节省空间。UTF-16的字节序有大尾序(big-endian)和小尾序(little-endian)之别。

pypinyin

pip install pypinyin
项目地址: https://github.com/mozillazg/python-pinyin
文档:
https://pypinyin.readthedocs.io/zh_CN/master/index.html
https://fishc.com.cn/thread-147575-1-1.html

单字拼音预测有误/远古多音字问题:

pypinyin.pinyin('重',heteronym=True) # [['zhòng', 'chóng', 'tóng']] tóng?
https://github.com/mozillazg/python-pinyin/issues/263
https://github.com/mozillazg/python-pinyin/issues/198

解决方法:替换默认字库
pip install pypinyin-dict

from pypinyin_dict.pinyin_data import cc_cedict
cc_cedict.load()

通过拼音索引汉字

import pypinyin as pypy
from pypinyin_dict.pinyin_data import cc_cedict
import json

cc_cedict.load()


def gb2312():
    s = []
    # 一级汉字3755个
    # for i in range(176, 216):
    #     for j in range(161, 255):
    for i in range(0xB0, 0xF7 + 1):
        for j in range(0xA1, 0xFE + 1):
            try:
                c = (bytes([i]) + bytes([j])).decode('gb2312')
            except:
                # print(i, j, 'error')
                continue
            # print(c, end=' ')
            s.append(c)
    print(len(s))  # 6763
    return s


hanzis = [chr(i) for i in range(0x4E00, 0x9FA6)]  # unicode 20902个汉字
hanzis = gb2312()  # gb2312 6737个汉字

dict = {}
for hanzi in hanzis:  #'重'
    pinyins = pypy.pinyin(hanzi, style=pypy.NORMAL, heteronym=True)[0]
    for pinyin in pinyins:
        if pinyin not in dict:
            dict[pinyin] = [hanzi]
        else:
            dict[pinyin].append(hanzi)
# print(dict)

# cc_cedict字库 , gb2312汉字
print(dict['qun'])  # ['裙', '群', '逡', '麇']
print(dict['zhi'])


'''
# 写入文件
with open('dict.json', 'w') as f:  # dict转josn
    json.dump(dict, f)

# 读取json
load_dict = []
with open('dict.json', 'r') as f:
    load_dict = json.load(f)
print(load_dict['cai'])
'''


这篇关于pypinyin的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程