python将汉字转化为拼音
安装
依赖python包:pypinyin 直接pip install pypinyin即可
常用方法及场景案例
from pypinyin import pinyin, lazy_pinyin, Style
# 汉字转化为拼音
hanzitopinyin = pinyin("中国")
# print(hanzitopinyin) # [['zhōng'], ['guó']]
# 开启多音字
duoyinzi = pinyin("和朴", heteronym=True)
# print(duoyinzi) # [['hé', 'hè', 'huò', 'huó', 'hú'], ['pǔ', 'pò', 'pū', 'pō', 'piáo']]
# 设置风格 FIRST_LETTER首字母风格,只返回拼音的首字母部分。
style = pinyin("中心", style=Style.FIRST_LETTER)
# print(style) # [['z'], ['x']]
# 不考虑多音字的情况
ret = lazy_pinyin("中心")
# print(ret) # ['zhong', 'xin']
"""
需求场景:添加账号,传入中文姓名,将中文姓名自动转化为拼音,若有姓名重复,在后面按升序加1
如:传入张三,需要得到zhangs,已存在张三,需要得到zhangs1
"""
# 已存在用户
user_list = ["wumj", "qinsh", "liub"]
print("已经存在的用户有:{}".format(user_list))
def get_user(new_user_list):
"""
和已知用户比对,得到最终账号
:param new_user_list: 中文姓名转化后的账号名
:return:
"""
print("姓名转化后的用户有:{}".format(new_user_list))
username_list = []
for new_user in new_user_list:
i = 1
while True:
username = new_user
if username in user_list:
username = username + str(i)
i += 1
if username not in user_list:
username_list.append(username)
break
elif username not in user_list:
username_list.append(username)
break
print("最终需要添加的用户为:{}".format(username_list))
def name_to_user(name_list):
"""
将中文姓名按要求转化为拼音(账号样式)
:param name_list: 姓名列表
:return:
"""
new_user_list = []
for name in name_list:
# 将中文姓名转化为拼音
user = lazy_pinyin(name)
# print(user)
# 返回结果为 姓 和 名 的列表,账号由姓的拼音全称+名的第一个字母组成
user_len = len(user)
new_user = ""
i = 0
while i < user_len:
if i == 0:
new_user += user[i]
else:
new_user += user[i][:1]
i += 1
if i == user_len:
break
new_user_list.append(new_user)
# print(new_user_list)
get_user(new_user_list)
def main():
name_str = input("请输入中文姓名:")
# 输入姓名转化为列表
name_list = name_str.split()
name_to_user(name_list)
if __name__ == '__main__':
main()