python 汉字拼音库 pypinyin

这个库还是很好用的,这个库还是很简单的,中文注解,下面是源码,看注释就可以大致明白方法的意思
#!/usr/bin/env python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from copy import deepcopy
from itertools import chain from pypinyin.compat import text_type, callable_check
from pypinyin.constants import (
PHRASES_DICT, PINYIN_DICT,
RE_HANS, Style
)
from pypinyin.contrib import mmseg
from pypinyin.utils import simple_seg, _replace_tone2_style_dict_to_default
from pypinyin.style import auto_discover, convert as convert_style auto_discover() def seg(hans):
hans = simple_seg(hans)
ret = []
for x in hans:
if not RE_HANS.match(x): # 没有拼音的字符,不再参与二次分词
ret.append(x)
elif PHRASES_DICT:
ret.extend(list(mmseg.seg.cut(x)))
else: # 禁用了词语库,不分词
ret.append(x)
return ret def load_single_dict(pinyin_dict, style='default'):
"""载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}``
:param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type pinyin_dict: dict
"""
if style == 'tone2':
for k, v in pinyin_dict.items():
v = _replace_tone2_style_dict_to_default(v)
PINYIN_DICT[k] = v
else:
PINYIN_DICT.update(pinyin_dict) mmseg.retrain(mmseg.seg) def load_phrases_dict(phrases_dict, style='default'):
"""载入用户自定义的词语拼音库 :param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}``
:param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type phrases_dict: dict
"""
if style == 'tone2':
for k, value in phrases_dict.items():
v = [
list(map(_replace_tone2_style_dict_to_default, pys))
for pys in value
]
PHRASES_DICT[k] = v
else:
PHRASES_DICT.update(phrases_dict) mmseg.retrain(mmseg.seg) def to_fixed(pinyin, style, strict=True):
"""根据拼音风格格式化带声调的拼音. :param pinyin: 单个拼音
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 根据拼音风格格式化后的拼音字符串
:rtype: unicode
"""
return convert_style(pinyin, style=style, strict=strict, default=pinyin) def _handle_nopinyin_char(chars, errors='default'):
"""处理没有拼音的字符"""
if callable_check(errors):
return errors(chars) if errors == 'default':
return chars
elif errors == 'ignore':
return None
elif errors == 'replace':
if len(chars) > 1:
return ''.join(text_type('%x' % ord(x)) for x in chars)
else:
return text_type('%x' % ord(chars)) def handle_nopinyin(chars, errors='default'):
py = _handle_nopinyin_char(chars, errors=errors)
if not py:
return []
if isinstance(py, list):
return py
else:
return [py] def single_pinyin(han, style, heteronym, errors='default', strict=True):
"""单字拼音转换. :param han: 单个汉字
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 返回拼音列表,多音字会有多个拼音项
:rtype: list
"""
num = ord(han)
# 处理没有拼音的字符
if num not in PINYIN_DICT:
return handle_nopinyin(han, errors=errors) pys = PINYIN_DICT[num].split(',') # 字的拼音列表
if not heteronym:
return [to_fixed(pys[0], style, strict=strict)] # 输出多音字的多个读音
# 临时存储已存在的拼音,避免多音字拼音转换为非音标风格出现重复。
# TODO: change to use set
# TODO: add test for cache
py_cached = {}
pinyins = []
for i in pys:
py = to_fixed(i, style, strict=strict)
if py in py_cached:
continue
py_cached[py] = py
pinyins.append(py)
return pinyins def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True):
"""词语拼音转换. :param phrase: 词语
:param errors: 指定如何处理没有拼音的字符
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 拼音列表
:rtype: list
"""
py = []
if phrase in PHRASES_DICT:
py = deepcopy(PHRASES_DICT[phrase])
for idx, item in enumerate(py):
py[idx] = [to_fixed(item[0], style=style, strict=strict)]
else:
for i in phrase:
single = single_pinyin(i, style=style, heteronym=heteronym,
errors=errors, strict=strict)
if single:
py.append(single)
return py def _pinyin(words, style, heteronym, errors, strict=True):
"""
:param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
不存在混合的情况。
"""
pys = []
# 初步过滤没有拼音的字符
if RE_HANS.match(words):
pys = phrase_pinyin(words, style=style, heteronym=heteronym,
errors=errors, strict=strict)
return pys py = handle_nopinyin(words, errors=errors)
if py:
pys.append(py)
return pys def pinyin(hans, style=Style.TONE, heteronym=False,
errors='default', strict=True):
"""将汉字转换为拼音. :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
可以使用自己喜爱的分词模块对字符串进行分词处理,
只需将经过分词处理的字符串列表传进来就可以了。
:type hans: unicode 字符串或字符串列表
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.TONE` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param errors: 指定如何处理没有拼音的字符 * ``'default'``: 保留原始字符
* ``'ignore'``: 忽略该字符
* ``'replace'``: 替换为去掉 ``\\u`` 的 unicode 编码字符串
(``'\\u90aa'`` => ``'90aa'``)
* callable 对象: 回调函数之类的可调用对象。如果 ``errors``
参数 的值是个可调用对象,那么程序会回调这个函数:
``func(char)``:: def foobar(char):
return 'a'
pinyin('あ', errors=foobar) :param heteronym: 是否启用多音字
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:return: 拼音列表
:rtype: list :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常 Usage:: >>> from pypinyin import pinyin, Style
>>> import pypinyin
>>> 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)
[['zho1ng'], ['xi1n']]
>>> pinyin('中心', style=Style.CYRILLIC)
[['чжун1'], ['синь1']]
"""
# 对字符串进行分词处理
if isinstance(hans, text_type):
han_list = seg(hans)
else:
han_list = chain(*(seg(x) for x in hans))
pys = []
for words in han_list:
pys.extend(_pinyin(words, style, heteronym, errors, strict=strict))
return pys def slug(hans, style=Style.NORMAL, heteronym=False, separator='-',
errors='default', strict=True):
"""生成 slug 字符串. :param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param heteronym: 是否启用多音字
:param separstor: 两个拼音间的分隔符/连接符
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:return: slug 字符串. :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常 :: >>> import pypinyin
>>> from pypinyin import Style
>>> pypinyin.slug('中国人')
'zhong-guo-ren'
>>> pypinyin.slug('中国人', separator=' ')
'zhong guo ren'
>>> pypinyin.slug('中国人', style=Style.FIRST_LETTER)
'z-g-r'
>>> pypinyin.slug('中国人', style=Style.CYRILLIC)
'чжун1-го2-жэнь2'
"""
return separator.join(chain(*pinyin(hans, style=style, heteronym=heteronym,
errors=errors, strict=strict)
)) def lazy_pinyin(hans, style=Style.NORMAL, errors='default', strict=True):
"""不包含多音字的拼音列表. 与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音. :param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`。
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:return: 拼音列表(e.g. ``['zhong', 'guo', 'ren']``)
:rtype: list :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常 Usage:: >>> from pypinyin import lazy_pinyin, Style
>>> import pypinyin
>>> lazy_pinyin('中心')
['zhong', 'xin']
>>> lazy_pinyin('中心', style=Style.TONE)
['zhōng', 'xīn']
>>> lazy_pinyin('中心', style=Style.FIRST_LETTER)
['z', 'x']
>>> lazy_pinyin('中心', style=Style.TONE2)
['zho1ng', 'xi1n']
>>> lazy_pinyin('中心', style=Style.CYRILLIC)
['чжун1', 'синь1']
"""
return list(chain(*pinyin(hans, style=style, heteronym=False,
errors=errors, strict=strict)))

在写代码的时候还是会经常用到的,比如商品排列,姓名按照首字母罗列

1.先讲讲简单的方法解析

from pypinyin import pinyin, lazy_pinyin, Style, load_phrases_dict, load_single_dict
from pypinyin.style import register print(pinyin('你好')) # [['nǐ'], ['hǎo']]
print(pinyin('中心', heteronym=True)) # 启用多音字模式 # [['zhōng', 'zhòng'], ['xīn']]
print(pinyin('中心', style=Style.FIRST_LETTER)) # 设置拼音风格,第一个字母 [['z'], ['x']]
print(pinyin('中心', style=Style.TONE2, heteronym=True)) # [['zho1ng', 'zho4ng'], ['xi1n']]
print(lazy_pinyin('中心')) # 不考虑多音字的情况 # ['zhong', 'xin'] ##########处理不包含拼音的字符
# default (默认行为): 不做任何处理,原样返回:
print(lazy_pinyin('你好☆☆')) # ['ni', 'hao', '☆☆']
# ignore : 忽略该字符
print(lazy_pinyin('你好☆☆', errors='ignore')) # ['ni', 'hao']
# replace : 替换为去掉 \u 的 unicode 编码
print(lazy_pinyin('你好☆☆', errors='replace')) # ['ni', 'hao', '26062606']
# callable 对象 : 提供一个回调函数,接受无拼音字符(串)作为参数, 支持的返回值类型: unicode 或 list ([unicode, …]) 或 None 。
print(lazy_pinyin('你好☆☆', errors=lambda x: 'star')) # ['ni', 'hao', 'star'] ########### 自定义拼音库
print(lazy_pinyin('还没', style=Style.TONE2))
load_phrases_dict({'桔子': [['jú'], ['zǐ']]}) # 增加 "桔子" 词组,可以自己定义
print(lazy_pinyin('桔子', style=Style.TONE2)) load_single_dict({ord('还'): 'hái,huán'}) # 调整 "还" 字的拼音顺序
print(lazy_pinyin('还没', style=Style.TONE2)) ###########自定义拼音风格
@register('kiss')
def kiss(mypinyin, **kwargs):
return '

python之pypinyin的更多相关文章

  1. Python 汉字转拼音库 pypinyin

    一.初衷: 一些开源软件的配置文件中识别区分的部分用英文,那么我们在批量生成配置文件的时候,可以从CMDB导入汉字(idc_name), 然后将它转换成拼音,再或者拼接上IP地址,以便更准确的识别.例 ...

  2. Python Thrift 简单示例

    本文基于Thrift-0.10,使用Python实现服务器端,使用Java实现客户端,演示了Thrift RPC调用示例.Java客户端提供两个字符串参数,Python服务器端计算这两个字符串的相似度 ...

  3. python 全栈开发,Day133(玩具与玩具之间的对话,基于jieba gensim pypinyin实现的自然语言处理,打包apk)

    先下载github代码,下面的操作,都是基于这个版本来的! https://github.com/987334176/Intelligent_toy/archive/v1.6.zip 注意:由于涉及到 ...

  4. python处理汉字转拼音pypinyin

    主要是pypinyin 包,官网: http://pypinyin.readthedocs.io/zh_CN/master/index.html jieba包,主要是用来分词的,我之前的博文有介绍:h ...

  5. Python 中拼音库 PyPinyin 的用法【华为云技术分享】

    [摘要] 最近碰到了一个问题,项目中很多文件都是接手过来的中文命名的一些素材,结果在部署的时候文件名全都乱码了,导致项目无法正常运行. 后来请教了一位大佬怎么解决文件名乱码的问题,他说这个需要正面解决 ...

  6. python拼音库pypinyin库详解

    # -*- coding: utf-8 -*- # @Author : FELIX # @Date : 2018/6/30 9:20 from pypinyin import pinyin, lazy ...

  7. python 各种开源库

    测试开发 来源:https://www.jianshu.com/p/ea6f7fb69501 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. 链接 sel ...

  8. python之多线程 queue 实践 筛选有效url

    0.目录 1.背景 某号码卡申请页面通过省份+城市切换归属地,每次返回10个号码. 通过 Fiddler 抓包确认 url 关键参数规律: provinceCode 两位数字 cityCode 三位数 ...

  9. Python开源框架、库、软件和资源大集合

    A curated list of awesome Python frameworks, libraries, software and resources. Inspired by awesome- ...

随机推荐

  1. Java中的注解到底是如何工作的?

    作者:人晓 www.importnew.com/10294.html 自Java5.0版本引入注解之后,它就成为了Java平台中非常重要的一部分.开发过程中,我们也时常在应用代码中会看到诸如@Over ...

  2. python中datetime模块中strftime/strptime函数

    f==format p==parse 1.获取当前时间(日期格式) from datetime import datetime datetime.now()#输出 datetime.datetime( ...

  3. 纯Delphi 原生写的 上传到七牛的功能

    上传文件到七牛, 支持分片分段上传, 适用于Delphi XE, 10等新版本 分两个函数: uploadToQiniu 和 directUploadToQiniu uploadToQiniu 这个函 ...

  4. 【java】自定义排序

    使用Comparable接口 这里定义了一个类Node,有两个属性,id,age. 排序方法是,先根据id升序排,id一样,age降序排. 里面有一个compareTo方法.返回值有三个 1. < ...

  5. XStream的简单使用

    XStream XStream是一个java对象和xml相互转换的工具 创建XStream对象:XStream stream = new XStream() Java对象转换成xml:stream . ...

  6. Spring注解之@Component、@Controller、@Service、@Repository

    目录 1.使用这四个注解的前提 2.详解@Component 3. @Service("XXX")或者@Service(value = "XXX")情况 4.总 ...

  7. git常用操作命令归纳

    git开始 全局配置:配置用户名和e-mail地址 $ git config --global user.name"Your Name" $ git config --global ...

  8. go构造函数

    go构造函数 结构体没有构造函数,你可以创建一个函数返回一个相应类型的实例代替(类似一个工厂): func NewSaiyan(name string, power int) *Saiyan { re ...

  9. ArrayList,LinkedList,Vector集合的认识

    最近在温习Java集合部分,花了三天时间读完了ArrayList与LinkedList以及Vector部分的源码.之前都是停留在简单使用ArrayList的API,读完源码看完不少文章后总算是对原理方 ...

  10. go解析markdown转成html

    一.代码 package main import ( "fmt" "github.com/microcosm-cc/bluemonday" "gith ...