API¶
拼音风格:
风格 | 值 | 含义 |
---|---|---|
pypinyin.NORMAL | 0 | 普通风格,不带声调。如: 中国 -> zhong guo |
pypinyin.TONE | 1 | 声调风格1,拼音声调在韵母第一个字母上(默认风格)。如: 中国 -> zhōng guó |
pypinyin.TONE2 | 2 | 声调风格2,即拼音声调在各个拼音之后,用数字 [0-4] 进行表示。如: 中国 -> zho1ng guo2 |
pypinyin.INITIALS | 3 | 声母风格,只返回各个拼音的声母部分。如: 中国 -> zh g |
pypinyin.FIRST_LETTER | 4 | 首字母风格,只返回拼音的首字母部分。如: 中国 -> z g |
pypinyin.FINALS | 5 | 韵母风格1,只返回各个拼音的韵母部分,不带声调。如: 中国 -> ong uo |
pypinyin.FINALS_TONE | 6 | 韵母风格2,带声调,声调在韵母第一个字母上。如:中国 -> ōng uó |
pypinyin.FINALS_TONE2 | 7 | 韵母风格2,带声调,声调在各个拼音之后,用数字 [0-4] 进行表示。如: 中国 -> o1ng uo2 |
-
pypinyin.
pinyin
(hans, style=1, heteronym=False, errors=u'default')[source]¶ 将汉字转换为拼音.
Parameters: - hans (unicode 字符串或字符串列表) –
汉字字符串(
u'你好吗'
)或列表([u'你好', u'吗']
).如果用户安装了
jieba
, 将使用jieba
对字符串进行 分词处理。可以通过传入列表的方式禁用这种行为。也可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。
- style – 指定拼音风格
- errors –
指定如何处理没有拼音的字符
'default'
: 保留原始字符'ignore'
: 忽略该字符'replace'
: 替换为去掉\u
的 unicode 编码字符串 (u'\u90aa'
=>u'90aa'
)- callable 对象: 回调函数之类的可调用对象。如果
erros
参数 的值是个可调用对象,那么程序会回调这个函数:func(char)
:def foobar(char): return 'a' pinyin(u'あ', errors=foobar)
- heteronym – 是否启用多音字
Returns: 拼音列表
Return type: list
Usage:
>>> from pypinyin import pinyin >>> import pypinyin >>> pinyin(u'中心') [[u'zhōng'], [u'xīn']] >>> pinyin(u'中心', heteronym=True) # 启用多音字模式 [[u'zhōng', u'zhòng'], [u'xīn']] >>> pinyin(u'中心', style=pypinyin.INITIALS) # 设置拼音风格 [[u'zh'], [u'x']] >>> pinyin(u'中心', style=pypinyin.TONE2) [[u'zho1ng'], [u'xi1n']]
- hans (unicode 字符串或字符串列表) –
-
pypinyin.
slug
(hans, style=0, heteronym=False, separator=u'-', errors=u'default')[source]¶ 生成 slug 字符串.
Parameters: - hans (unicode or list) – 汉字
- style – 指定拼音风格
- heteronym – 是否启用多音字
- separstor – 两个拼音间的分隔符/连接符
- errors – 指定如何处理没有拼音的字符,详情请参考
pinyin()
Returns: slug 字符串.
>>> import pypinyin >>> pypinyin.slug(u'中国人') u'zhong-guo-ren' >>> pypinyin.slug(u'中国人', separator=u' ') u'zhong guo ren' >>> pypinyin.slug(u'中国人', style=pypinyin.INITIALS) u'zh-g-r'
-
pypinyin.
lazy_pinyin
(hans, style=0, errors=u'default')[source]¶ 不包含多音字的拼音列表.
与
pinyin()
的区别是返回的拼音是个字符串, 并且每个字只包含一个读音.Parameters: - hans (unicode or list) – 汉字
- style – 指定拼音风格
- errors – 指定如何处理没有拼音的字符,详情请参考
pinyin()
Returns: 拼音列表(e.g.
['zhong', 'guo', 'ren']
)Return type: list
Usage:
>>> from pypinyin import lazy_pinyin >>> import pypinyin >>> lazy_pinyin(u'中心') [u'zhong', u'xin'] >>> lazy_pinyin(u'中心', style=pypinyin.TONE) [u'zhōng', u'xīn'] >>> lazy_pinyin(u'中心', style=pypinyin.INITIALS) [u'zh', u'x'] >>> lazy_pinyin(u'中心', style=pypinyin.TONE2) [u'zho1ng', u'xi1n']