Python implements a library that converts Chinese characters into Hanyu Pinyin

Source: Internet
Author: User
The example in this paper describes the python implementation of the Chinese characters into Hanyu Pinyin library. Share to everyone 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, click here to download this site.

#!/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.P Ath.exists (self.dict_file): Raise IOError ("Notfoundfile") with file (Self.dict_file) as F_obj:for f_line in F_obj.rea Dlines (): 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, unicod E): 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.hanzi2pi Nyin (string=string) if split = = "": Return result Else:return split.join (result) if __name__ = = "__main__": Test = P Inyin () Test.load_word () sTring = "Welcome to print" In:%s "% string print" out:%s "% str (Test.hanzi2pinyin (string=string)) print" Out:%s "% Test.hanz I2pinyin_split (string=string, split= "-")

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.