python汉字转换为拼音

使用pypinyin包

pip install pypinyin

from pypinyin import pinyin, NORMAL
# 将汉字转换为拼音,pinyin()转换后是列表,不加style转换后带声调
pos = 1
for piny in pinyin(self.name, style=NORMAL):
    piny = ''.join(piny)
    print(piny)
    if (1 == pos) or (2 == pos):
        piny = piny.capitalize()
    self.namePinYin += piny
    pos += 1

附字符串与列表之间的转换:

(1)字符串转换为列表

str1 = "hi hello world"
print(str1.split(" "))
输出:
['hi', 'hello', 'world']

(2)列表转换为字符串

l = ["hi","hello","world"]
print(" ".join(l))
输出:
hi hello world

猜你喜欢

转载自blog.csdn.net/Leo062701/article/details/81213568