想在文档中自动把汉字的拼音标注上去,可是很难,用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("六只蚂蚁学汉字"))
=================================================