当前位置:Gxlcms > Python > python实现将汉字转换成汉语拼音的库

python实现将汉字转换成汉语拼音的库

时间:2021-07-01 10:21:17 帮助过:58人阅读

本文实例讲述了python实现将汉字转换成汉语拼音的库。分享给大家供大家参考。具体分析如下:

下面的这个python库可以很容易的将汉字转换成拼音,其中用到了一个word.data 的字典,可点击此处本站下载。

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. __version__ = '0.9'
  4. __all__ = ["PinYin"]
  5. import os.path
  6. class PinYin(object):
  7. def __init__(self, dict_file='word.data'):
  8. self.word_dict = {}
  9. self.dict_file = dict_file
  10. def load_word(self):
  11. if not os.path.exists(self.dict_file):
  12. raise IOError("NotFoundFile")
  13. with file(self.dict_file) as f_obj:
  14. for f_line in f_obj.readlines():
  15. try:
  16. line = f_line.split(' ')
  17. self.word_dict[line[0]] = line[1]
  18. except:
  19. line = f_line.split(' ')
  20. self.word_dict[line[0]] = line[1]
  21. def hanzi2pinyin(self, string=""):
  22. result = []
  23. if not isinstance(string, unicode):
  24. string = string.decode("utf-8")
  25. for char in string:
  26. key = '%X' % ord(char)
  27. result.append(self.word_dict.get(key,char).split()[0][:-1].lower())
  28. return result
  29. def hanzi2pinyin_split(self, string="", split=""):
  30. result = self.hanzi2pinyin(string=string)
  31. if split == "":
  32. return result
  33. else:
  34. return split.join(result)
  35. if __name__ == "__main__":
  36. test = PinYin()
  37. test.load_word()
  38. string = "欢迎来到"
  39. print "in: %s" % string
  40. print "out: %s" % str(test.hanzi2pinyin(string=string))
  41. print "out: %s" % test.hanzi2pinyin_split(string=string, split="-")

希望本文所述对大家的Python程序设计有所帮助。

人气教程排行