1. 程式人生 > >Python之漢字轉拼音

Python之漢字轉拼音

 1.安裝pypinyin

pip install pypinyin

 2.具體程式碼如下

from pypinyin import pinyin,Style

#
# singer_dict = {
#
#     "first": [{"name": "周杰倫",
#                "singer": "青花瓷"}],
#
#     "second": [{"name": "毛不易",
#                 "singer": "消愁"}],
#     "third": [{"name": "張傑",
#                "singer": "逆戰"}],
#
# }

singer_dict = {

    "first": [{"name": "周杰倫",
               "singer": "青花瓷"},

              {"name": "毛不易",
               "singer": "消愁"},
              {"name": "張傑",
               "singer": "逆戰"}],

}
p = pinyin("周杰倫", style=Style.FIRST_LETTER)
# p:[['z'], ['j'], ['l']]
print(p[0][0])
# z
for key, singers in singer_dict.items():
    for singer in singers:
        first_c = pinyin(singer.get("name"), style=Style.FIRST_LETTER)[0][0]
        singer['first_c'] = first_c.upper()
print(singer_dict)