使用python输出所有汉字的拼音hàn-zì-pīn-yīn

想在文档中自动把汉字的拼音标注上去,可是很难,用excel或者word来辅助,操作也不方便。

万能的python,加上大神写的拼音工具插件xpinyin,几行代码,就可以把所有汉字的拼音输出!极为强悍!

1、安装xpinyin库:使用【pip install xpinyin】自动安装,或者下载后手工安装(进入下载后的插件目录,运行 python setup.py install)

     下载网址为:https://pypi.org/project/xpinyin/0.4.9/

2、脚本如下:

==================================================================

# -*- coding: utf-8 -*-

from xpinyin import Pinyin

def print_unicode(start, end):

        p = Pinyin()

        Start = start

        while Start <= end:

                ustr = '\u' + hex(Start)[2:]

                index = Start - start + 1

     print str(index) + '\t' + ustr.decode('unicode-escape') + '\t' + p.get_pinyin(ustr.decode('unicode-escape'), show_tone_marks=True)

                Start = Start + 1

 

# 输出所有汉字的拼音

print_unicode(0x4e00, 0x9fbf)

==============================================================

3、xpinyin的几种用法

# default splitter is `-`

p.get_pinyin(u"上海")

# 'shang-hai'

# show tone marks

p.get_pinyin(u"上海", show_tone_marks=True)

# 'shàng-hǎi'

# remove splitter

p.get_pinyin(u"上海", '')

# 'shanghai'

# set splitter as whitespace

p.get_pinyin(u"上海", ' ')

# 'shang hai'

p.get_initial(u"上")

# 'S'

p.get_initials(u"上海")

# 'S-H'

p.get_initials(u"上海", u'')

# 'SH'

p.get_initials(u"上海", u' ')

# 'S H'

 

 

补充说明:

使用pypinyin库也很方便。把代码放下面(没有亲自运行过)

=========================================================

import pypinyin

# 不带声调的(style=pypinyin.NORMAL)

def hp(word):

        s = ''

        for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):

        s += ''.join(i)

        return s

       

# 带声调的(默认)

def hp2(word):

        s = ''

        for i in pypinyin.pinyin(word):

        s = s + ''.join(i) + " "

        return s

 

if __name__ == "__main__":

        print(hp("六只蚂蚁学汉字"))

        print(hp2("六只蚂蚁学汉字"))

=================================================

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值