python实现汉字转拼音的2种方法

在浏览博客时,偶然看到了用python将汉字转为拼音的第三方包,但是在实现的过程中发现一些参数已经更新,现在将两种方法记录一下。

xpinyin

在一些博客中看到,如果要转化成带音节的拼音,需要传递参数,‘show_tone_marks=True',但我在实际使用时发现,已经没有这个参数了,变成了tone_marks,其它的参数和使用方法,一看就明白了,写的很清楚。

看下源码:

class Pinyin(object):"""translate chinese hanzi to pinyin by python, inspired by flyerhzm's`chinese\_pinyin`_ gemusage-----::>>> from xpinyin import Pinyin>>> p = Pinyin()>>> # default splitter is `-`>>> p.get_pinyin(u"上海")'shang-hai'>>> # show tone marks>>> p.get_pinyin(u"上海", tone_marks='marks')'shàng-hǎi'>>> p.get_pinyin(u"上海", tone_marks='numbers')>>> 'shang4-hai3'>>> # remove splitter>>> p.get_pinyin(u"上海", '')'shanghai'>>> # set splitter as whitespace>>> p.get_pinyin(u"上海", ' ')'shang hai'>>> p.get_initial(u"上")'S'>>> p.get_initials(u"上海")'S-H'>>> p.get_initials(u"上海", u'')'SH'>>> p.get_initials(u"上海", u' ')'S H'请输入utf8编码汉字.. _chinese\_pinyin: https://github.com/flyerhzm/chinese_pinyin"""

安装xpinyin

pip install xpinyin

代码:

from xpinyin import Pinyin# 实例拼音转换对象
p = Pinyin()
# 进行拼音转换
ret = p.get_pinyin(u"汉语拼音转换", tone_marks='marks')
ret1 = p.get_pinyin(u"汉语拼音转换", tone_marks='numbers')
print(ret+'\n'+ret1)
# 得到转化后的结果
# hàn-yǔ-pīn-yīn-zhuǎn-huàn
# han4-yu3-pin1-yin1-zhuan3-huan4

pypinyin

与xpinyin相比,pypinyin更强大。

源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom copy import deepcopy
from itertools import chainfrom 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_styleauto_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 retdef 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] = velse: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] = velse: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 charselif errors == 'ignore':return Noneelif 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', heteronym=True):py = _handle_nopinyin_char(chars, errors=errors)if not py:return []if isinstance(py, list):# 包含多音字信息if isinstance(py[0], list):if heteronym:return py# [[a, b], [c, d]]# [[a], [c]]return [[x[0]] for x in py]return [[i] for i in 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, heteronym=heteronym)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 cachepy_cached = {}pinyins = []for i in pys:py = to_fixed(i, style, strict=strict)if py in py_cached:continuepy_cached[py] = pypinyins.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.extend(single)return pydef _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 pyspy = handle_nopinyin(words, errors=errors, heteronym=heteronym)if py:pys.extend(py)return pysdef 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: 指定如何处理没有拼音的字符。详见 :ref:`handle_no_pinyin`* ``'default'``: 保留原始字符* ``'ignore'``: 忽略该字符* ``'replace'``: 替换为去掉 ``\\u`` 的 unicode 编码字符串(``'\\u90aa'`` => ``'90aa'``)* callable 对象: 回调函数之类的可调用对象。: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 pysdef 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)))

安装:

pip install pypinyin

使用:

import pypinyin# 不带声调的(style=pypinyin.NORMAL)
def pinyin(word):s = ''for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):s += ''.join(i)return s# 带声调的(默认)
def yinjie(word):s = ''# heteronym=True开启多音字for i in pypinyin.pinyin(word, heteronym=True):s = s + ''.join(i) + " "return sif __name__ == "__main__":print(pinyin("忠厚传家久"))print(yinjie("诗书继世长"))

利用python实现汉字转拼音的2种方法相关推荐

  1. PHP汉字转拼音的两种方法+PHP提取汉字(中文)方法

    方法一:根据ASCII码转换,GB2312库对多音字也无能为力. GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理朱镕基的"镕"字. GB2312中 ...

  2. python 条形图填充疏密_教你利用Python玩转histogram直方图的五种方法

    直方图 直方图是一个可以快速展示数据概率分布的工具,直观易于理解,并深受数据爱好者的喜爱.大家平时可能见到最多就是 matplotlib,seaborn 等高级封装的库包,类似以下这样的绘图. 本篇博 ...

  3. Java/Android中汉字转拼音的两种方法,优劣比较

    一.前言 在我们的开发中,有时会有这样的需求,就是联系人列表按照拼音顺序排列(如通讯录).于是,我也在网上搜到了许多这类的文章,就两种最常见的做法在此进行简单的比较和分析 二.汉字转拼音的方法 使用第 ...

  4. Android中汉字转拼音的两种方法,优劣比较

    一.前言 在我们的开发中,有时会有这样的需求,就是联系人列表按照拼音顺序排列(如通讯录).于是,我也在网上搜到了许多这类的文章,就两种最常见的做法在此进行简单的比较和分析 二.汉字转拼音的方法 使用第 ...

  5. python 直方图的绘制方法全解_教你利用Python玩转histogram直方图的五种方法

    直方图 直方图是一个可以快速展示数据概率分布的工具,直观易于理解,并深受数据爱好者的喜爱.大家平时可能见到最多就是 matplotlib,seaborn 等高级封装的库包,类似以下这样的绘图. 本篇博 ...

  6. 【Python】使用python实现汉字转拼音(2018.12更新)

    在浏览博客时,偶然看到了用python将汉字转为拼音的第三方包,但是在实现的过程中发现一些参数已经更新,现在将两种方法记录一下. xpinyin 在一些博客中看到,如果要转化成带音节的拼音,需要传递参 ...

  7. python处理word或者pdf文件_利用python程序生成word和PDF文档的方法

    一.程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用fr ...

  8. python监控短信_利用Python实现手机短信监控通知的方法

    日常运维工作中,通常是邮件报警机制,但邮件可能不被及时查看,导致问题出现得不到及时有效处理.所以想到用Python实现发短信功能,当监控到问题出现时,短信报警,使问题能得到及时的处理.当然,我相信,用 ...

  9. python json 转csv_利用python将json数据转换为csv格式的方法

    假设.json文件中存储的数据为: {"type": "Point", "link": "http://www.dianping. ...

最新文章

  1. 中国电子学会图形化四级编程题:绘制雪花
  2. 将一个c 语言源程序文件中所有注释去掉后,存入另一个文件.,C实验内容.doc
  3. PHP工程师需要掌握的知识(转载)
  4. if函数python作用_if __name__== __main__ 的意思(作用)python代码复用
  5. Python MQTT订阅获取发布信息字典过滤
  6. leetcode894.AllPossibleFullBinaryTrees
  7. 51Nod 1131 - 覆盖数字的数量(分类讨论)
  8. java基础教程第3版_java基础教程第3版习题解答
  9. 吸引力法则~助攻遇到自己的另一半
  10. 忽现的Mybatis foreach 失效记录.
  11. 多媒体课件是不是计算机软件,计算机应用基础与信息处理多媒体课件制作.doc...
  12. STM32HAL库-内部Flash在指定页读写保护示例
  13. Java程序从编写到运行
  14. 才智杂志社才智杂志才智编辑部2022年第36期目录
  15. VLINK 的更新版本
  16. 计算机提取公式算等差平均,高中数学统计与概率主线分析.ppt
  17. WPViewPDF Crack,Delphi 和 .NET 的PDF 查看组件
  18. SVM学习总结(一)如何学习SVM
  19. 视频 | 马云:如果有天阿里不在了,我们也要为世界留下这三样
  20. 重现期Matlab\Python程序(Gumbel和广义极值分布)

热门文章

  1. LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60
  2. 当英文遇上汉语 就知道汉语有多强大了
  3. 十二星座html网页设计作品,十二星座的专属设计风格
  4. UESTC 1607 大学生足球联赛 构造、蛇形安排赛程表
  5. c++ MFC 根据屏幕分辨率变化自动调整控件位置和大小
  6. MapReduce各个执行阶段
  7. FFMPEG,vlc介绍和视频直播,obs(zz)
  8. 千图网爬图片(BeautifulSoup)
  9. mysql中如何统计数据_mysql中的数据统计方法
  10. 计算机二级c语言题2016,2016年计算机二级《C语言》专项练习题及答案