python實(shí)現(xiàn)將漢字轉(zhuǎn)換成漢語拼音的庫
本文實(shí)例講述了python實(shí)現(xiàn)將漢字轉(zhuǎn)換成漢語拼音的庫。分享給大家供大家參考。具體分析如下:
下面的這個python庫可以很容易的將漢字轉(zhuǎn)換成拼音,其中用到了一個word.data 的字典,可點(diǎn)擊此處本站下載。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__version__ = '0.9'
__all__ = ["PinYin"]
import os.path
class PinYin(object):
def __init__(self, dict_file='word.data'):
self.word_dict = {}
self.dict_file = dict_file
def load_word(self):
if not os.path.exists(self.dict_file):
raise IOError("NotFoundFile")
with file(self.dict_file) as f_obj:
for f_line in f_obj.readlines():
try:
line = f_line.split(' ')
self.word_dict[line[0]] = line[1]
except:
line = f_line.split(' ')
self.word_dict[line[0]] = line[1]
def hanzi2pinyin(self, string=""):
result = []
if not isinstance(string, unicode):
string = string.decode("utf-8")
for char in string:
key = '%X' % ord(char)
result.append(self.word_dict.get(key,char).split()[0][:-1].lower())
return result
def hanzi2pinyin_split(self, string="", split=""):
result = self.hanzi2pinyin(string=string)
if split == "":
return result
else:
return split.join(result)
if __name__ == "__main__":
test = PinYin()
test.load_word()
string = "歡迎來到腳本之家"
print "in: %s" % string
print "out: %s" % str(test.hanzi2pinyin(string=string))
print "out: %s" % test.hanzi2pinyin_split(string=string, split="-")
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python協(xié)程的2種實(shí)現(xiàn)方式分享
在?Python?中,協(xié)程(Coroutine)是一種輕量級的并發(fā)編程方式,可以通過協(xié)作式多任務(wù)來實(shí)現(xiàn)高效的并發(fā)執(zhí)行。本文主要介紹了Python實(shí)現(xiàn)協(xié)程的2種方式,希望對大家有所幫助2023-04-04
MAC平臺基于Python Appium環(huán)境搭建過程圖解
這篇文章主要介紹了MAC平臺基于Python Appium環(huán)境搭建過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
一步步教你用Python實(shí)現(xiàn)2048小游戲
相信2048這個游戲?qū)Υ蠹襾碚f一定不陌生,下面這篇文章就主要給大家介紹了怎么用Python實(shí)現(xiàn)2048小游戲,文中通過注釋與示例代碼介紹的很詳細(xì),相信對大家的理解和學(xué)習(xí)具有一定的參考借鑒價值,有需要的朋友們一起來看看吧。2017-01-01
WxPython開發(fā)之列表數(shù)據(jù)的自定義打印處理
這篇文章主要為大家詳細(xì)介紹了如何利用WxPython內(nèi)置的打印數(shù)據(jù)組件實(shí)現(xiàn)列表數(shù)據(jù)的自定義打印處理,以及對記錄進(jìn)行分頁等常規(guī)操作,需要的可以參考下2025-03-03
python神經(jīng)網(wǎng)絡(luò)之批量學(xué)習(xí)tf.train.batch函數(shù)示例
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)之批量學(xué)習(xí)tf.train.batch函數(shù)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python實(shí)現(xiàn)的守護(hù)進(jìn)程(Daemon)用法實(shí)例
這篇文章主要介紹了python實(shí)現(xiàn)的守護(hù)進(jìn)程(Daemon)用法,實(shí)例分析了Python進(jìn)程操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06

