Python3之常用包匯總


  Python包網站: https://pypi.org/

 

1. 繁體與簡體轉換(https://github.com/berniey/hanziconv.git)

 

pip install hanziconv

示例:

from hanziconv import HanziConv

def switch_hanzi(keyword):
    """
    漢字轉換(簡體<>繁體)
    :return:
    """
    simple_chinese = HanziConv.toSimplified(keyword)
    if simple_chinese == keyword:  # 簡體
        tradition_chinese = HanziConv.toTraditional(keyword)
        if tradition_chinese == simple_chinese:
            return
        return tradition_chinese
    else:
        return simple_chinese


keyword = '生活'
print(switch_hanzi(keyword))

keyword = '中國'
print(switch_hanzi(keyword))

 

2. 漢字轉拼音(https://github.com/mozillazg/python-pinyin)

pip install pypinyin
>>> 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.TONE3, heteronym=True)
[['zhong1', 'zhong4'], ['xin1']]
>>> pinyin('中心', style=Style.BOPOMOFO)  # 注音風格
[['ㄓㄨㄥ'], ['ㄒㄧㄣ']]
>>> lazy_pinyin('中心')  # 不考慮多音字的情況
['zhong', 'xin']

 

 

3. 拼音轉漢字(https://github.com/someus/Pinyin2Hanzi)

pip install Pinyin2Hanzi

示例:

from Pinyin2Hanzi import DefaultHmmParams
from Pinyin2Hanzi import viterbi

hmmparams = DefaultHmmParams()

## 2個候選
result = viterbi(hmm_params=hmmparams, observations=('ni', 'zhi', 'bu', 'zhi', 'dao'), path_num = 2)
for item in result:
    print(item.score, item.path)
'''輸出
1.3155294593897203e-08 ['', '', '', '', '']
3.6677865125992192e-09 ['', '', '', '', '']
'''

 

def get_similar_words(word, num=3):
    """
    獲取相似詞
    :param word: 單詞
    :param num: 返回詞匯數量
    """
    word_pinyin = lazy_pinyin(word)

    dagparams = DefaultDagParams()
    result = dag(dagparams, tuple(word_pinyin), path_num=num)
    # 拼接,去重
    words = set()
    for item in result:
        print(item.path)
        new_word = item.path[0] if len(item.path) == 1 else ''.join(item.path)
        words.add(new_word)

    similar_words = words - set([word])
    return list(similar_words)

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM