Skip to main content

汉字拼音转换工具.

Project description

Build Coverage PyPI version

将汉字转为拼音。可以用于汉字注音、排序、检索(Russian translation) 。

基于 hotoo/pinyin 开发。

特性

  • 根据词组智能匹配最正确的拼音。

  • 支持多音字。

  • 简单的繁体支持, 注音支持。

  • 支持多种不同拼音/注音风格。

安装

$ pip install pypinyin

文档

详细文档请访问:http://pypinyin.rtfd.io/

使用示例

Python 3(Python 2 下把 '中心' 替换为 u'中心' 即可):

>>> from pypinyin import pinyin, lazy_pinyin, Style
>>> 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.BOPOMOFO)  # 注音风格
[['ㄓㄨㄥ'], ['ㄒㄧㄣ']]
>>> pinyin('中心', style=Style.CYRILLIC)  # 俄语字母风格
[['чжун1'], ['синь1']]
>>> lazy_pinyin('中心')  # 不考虑多音字的情况
['zhong', 'xin']

命令行工具:

$ pypinyin 音乐
yīn yuè
$ pypinyin -h

FAQ

为什么没有 y, w, yu 几个声母?

声母风格(INITIALS)下,“雨”、“我”、“圆”等汉字返回空字符串,因为根据 《汉语拼音方案》 , y,w,ü (yu) 都不是声母,在某些特定韵母无声母时,才加上 y 或 w,而 ü 也有其特定规则。 —— @hotoo

如果你觉得这个给你带来了麻烦,那么也请小心一些无声母的汉字(如“啊”、“饿”、“按”、“昂”等)。 这时候你也许需要的是首字母风格(FIRST_LETTER)。 —— @hotoo

参考: hotoo/pinyin#57, #22, #27, #44

自定义了词典,但是结果没用使用自定义词典中的拼音信息?

自定义的词语在你使用的分词模块(比如:jieba)中没有被切分为一个词语, 可以考虑使用内置的最大匹配分词器来分词或者训练使用的分词模块。

>>> from pypinyin import pinyin, load_phrases_dict
>>> load_phrases_dict({'了局': [['liǎo'], ['jú']]})
>>> pinyin('了局啊')   # 使用 jieba 分词
Building prefix dict from the default dictionary ...
Dumping model to file cache /var/folders/s6/z9r_07h53pj_d4x7qjszwmbw0000gn/T/jieba.cache
Loading model cost 1.175 seconds.
Prefix dict has been built succesfully.
[['le'], ['jú'], ['a']]

>>> from pypinyin.contrib.mmseg import seg, retrain
>>> retrain(seg)     # 没有使用 load_phrases_dict 时可以不调用这个函数
>>> pinyin(seg.cut('了局啊'))  # 使用内置的最大匹配分词
[['liǎo'], ['jú'], ['a']]
>>>

拼音数据

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pypinyin-0.25.0.tar.gz (965.5 kB view hashes)

Uploaded Source

Built Distribution

pypinyin-0.25.0-py2.py3-none-any.whl (982.9 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page