import xpinyin
s = xpinyin.Pinyin() #一个实例化,以后了解
print(s.get_pinyin('小小军')) #get_pinyin方法,转出来的拼音,每一个汉字之间默认‘-’连接
print(s.get_pinyin('小小军',''))#传个参数,中间不用字符连接
from xpinyin import Pinyin
p = Pinyin()
print(p.get_pinyin("上海", show_tone_marks=True)) #标记声调
print(p.get_initial("上")) #一个汉字的拼音首字母大写
print(p.get_initials("上海")) #每个汉字的拼音首字母大写
摘自:https://pypi.org/project/xpinyin/
>>> from xpinyin import Pinyin
>>> p = Pinyin()
>>> # 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' python2,如果方法中传入变量,那么直接加前缀是不可以了。而是要将变量转为utf-8编码:
>>> wordvalue = '中国'
>>> wordvalue= unicode(wordvalue,'utf-8')
>>> s = p.get_initials(wordvalue, u'').lower()
'zg'
注意:python 3中最大的变化之一就是删除了Unicode类型。Python 3默认的是UTF-8编码。这意味着你可以在字符串或者变量名中使用Unciode字符集。
直接用s = p.get_initials(wordvalue, '').lower()即可,不用转码