Python3 如何实现汉字转换拼音?

目前常用的有两个包可以实现 Python 汉字转换拼音。

第一个是 pypinyin 比较有名,可以参考 pypinyin 官方 地址或者 GitHub 地址开发文档。

pypinyin 最初版本是基于 hotoo/pinyinjs 代码作为参考实现的,pypinyin 最大的优点是功能相对比较丰富。

>>> from pypinyin import pinyin, lazy_pinyin, Style
>>> pinyin('中心')  # or pinyin(['中心']),参数值为列表时表示输入的是已分词后的数据
[['zhōng'], ['xīn']]
>>> pinyin('中心', heteronym=True)  # 启用多音字模式
[['zhōng', 'zhòng'], ['xīn']]
>>> pinyin('中心', style=Style.FIRST_LETTER)  # 设置拼音风格
[['z'], ['x']]
>>> pinyin('中心', style=Style.TONE2, heteronym=True)
[['zho1ng', 'zho4ng'], ['xi1n']]
>>> pinyin('中心', style=Style.TONE3, heteronym=True)
[['zhong1', 'zhong4'], ['xin1']]
>>> pinyin('中心', style=Style.BOPOMOFO)  # 注音风格
[['ㄓㄨㄥ'], ['ㄒㄧㄣ']]
>>> lazy_pinyin('威妥玛拼音', style=Style.WADEGILES)
['wei', "t'o", 'ma', "p'in", 'yin']
>>> lazy_pinyin('中心')  # 不考虑多音字的情况
['zhong', 'xin']
>>> lazy_pinyin('战略', v_to_u=True)  # 不使用 v 表示 ü
['zhan', 'lüe']
# 使用 5 标识轻声
>>> lazy_pinyin('衣裳', style=Style.TONE3, neutral_tone_with_five=True)
['yi1', 'shang5']
# 变调  nǐ hǎo -> ní hǎo
>>> lazy_pinyin('你好', style=Style.TONE2, tone_sandhi=True)
['ni2', 'ha3o']

第二个是包是 xpinyin,相对于复杂的 pypinyin 功能没那么强大,但是 xpinyin 最大的优点是足够轻量和简单。

>>> from xpinyin import Pinyin
>>> p = Pinyin()
>>> # default splitter is `-`
>>> p.get_pinyin("上海")
'shang-hai'
>>> # show tone marks
>>> p.get_pinyin("上海", tone_marks='marks')
'shàng-hǎi'
>>> p.get_pinyin("上海", tone_marks='numbers')
>>> 'shang4-hai3'
>>> # remove splitter
>>> p.get_pinyin("上海", '')
'shanghai'
>>> # set splitter as whitespace
>>> p.get_pinyin("上海", ' ')
'shang hai'
>>> p.get_initial("上")
'S'
>>> p.get_initials("上海")
'S-H'
>>> p.get_initials("上海", '')
'SH'
>>> p.get_initials("上海", ' ')
'S H'
>>> # get_initials with retroflex, #39
>>> p.get_initials("上海", splitter='-', with_retroflex=True)
'SH-H'
>>> # New in version 0.7.0, get combinations of the multiple readings of the characters
>>> p.get_pinyins('模型', splitter=' ', tone_marks='marks')
['mó xíng', 'mú xíng']
>>> p.get_pinyins('模样', splitter=' ', tone_marks='marks')
['mó yáng', 'mó yàng', 'mó xiàng', 'mú yáng', 'mú yàng', 'mú xiàng']

两个包都可以实现汉字转换拼音的功能,如果只是想简单的拼音转换不涉及复杂的功能那么 xpinyin 可能是个更好的选择。

猜你喜欢

转载自blog.csdn.net/yilovexing/article/details/128904638
今日推荐