This article mainly introduces the python library for converting Chinese characters into Chinese pinyin, which involves Python calling word. the data field function is very useful for converting Chinese characters to pinyin. For more information, see the following example. Share it with you for your reference. The specific analysis is as follows:
The following python library can easily convert Chinese characters into pinyin, which uses a word. data Dictionary. you can click here to download it.
#! /Usr/bin/env python #-*-coding: UTF-8-*-_ version _ = '0. 9' _ all _ = ["PinYin"] import OS. pathclass 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] Character T: 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 = "Welcome to" print "in: % s" % string print "out: % s" % str (test. hanzi2pinyin (string = string) print "out: % s" % test. hanzi2pinyin_split (string = string, split = "-")
I hope this article will help you with Python programming.