栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python工具——pypinyin 汉字转换拼音

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python工具——pypinyin 汉字转换拼音

把汉字转成拼音后可以进行深度学习分类,做内容识别

1.安装

pip install pypinyin

将汉字转换为拼音并生成 slug 字符串

import pypinyin
from pypinyin import Style
content = pypinyin.slug('汉语拼音')
print(content)
# E:python>python pinyin.py
# han-yu-pin-yin

修改分隔字符串

import pypinyin
from pypinyin import Style
content = pypinyin.slug('汉语拼音',separator=' ')
print(content)
# E:python>python pinyin.py
# han yu pin yin

启用多音字模式

import pypinyin 
content = pypinyin.pinyin(u'单个', heteronym=True) # heteronym=False 不启用多音字
print(content)
# [['dān', 'chán', 'shàn'], ['gè', 'gàn', 'gě']]

 生成多音名字所有拼音列表

import pypinyin
from icecream import ic
from itertools import product

def load_pinyins(name):
    """通过名字加载拼音列表"""
    pinyins = []
    for char in name:
        pinyins = pinyins + pypinyin.pinyin(char, style=pypinyin.NORMAL, heteronym=True)
    # 通过笛卡尔积找到所有姓和名字的组合 product(*pinyins)
    return set(["".join(pinyins) for pinyins in product(*pinyins)]) 

 style设置拼音音调风格

from pypinyin import pinyin, Style

# (1)Style.TONE3音调显示在末尾
print(pinyin('单个',style=Style.TONE3))
# [['dan1'], ['ge4']]#数字为音调
print(pinyin('单个',style=Style.TONE3,heteronym=True))
# [['dan1', 'chan2', 'shan4'], ['ge4', 'gan4', 'ge3']]#数字为音调

# (2) Style.TONE2音调显示在韵母
print(pinyin('单个',style=Style.TONE2,heteronym=True))
# [['da1n', 'cha2n', 'sha4n'], ['ge4', 'ga4n', 'ge3']]#数字为音调

# (3)Style.TONE音调为手写格式
print(pinyin('单个',style=Style.TONE))
# [['dān'], ['gè']]
print(pinyin('单个',style=Style.TONE,heteronym=True))
# [['dān', 'chán', 'shàn'], ['gè', 'gàn', 'gě']]

# (4)pypinyin.NORMAL不显示音调
print(pinyin(u'单个', heteronym=True,style=pypinyin.NORMAL))
# [['dan', 'chan', 'shan'], ['ge', 'gan']]
print(pinyin(u'单个', style=pypinyin.NORMAL))
# [['dan'], ['ge']]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/529965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号