前言
在瀏覽博客時,偶然看到了用python將漢字轉為拼音的第三方包,但是在實現的過程中發現一些參數已經更新,現在將兩種方法記錄一下。
xpinyin
在一些博客中看到,如果要轉化成帶音節的拼音,需要傳遞參數,‘
show_tone_marks=True'
,但我在實際使用時發現,已經沒有這個參數了,變成了tone_marks,其它的參數和使用方法,一看就明白了,寫的很清楚。
看下源碼:
class Pinyin(object): """translate chinese hanzi to pinyin by python, inspired by flyerhzm's `chinese\_pinyin`_ gem usage ----- :: >>> 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 """
安裝:
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更強大。
安裝: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 s if __name__ == "__main__": print(pinyin("忠厚傳家久")) print(yinjie("詩書繼世長"))
源碼:
#!/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', 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 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.extend(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, heteronym=heteronym) if py: pys.extend(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: 指定如何處理沒有拼音的字符。詳見 :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 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)))
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
