fusenapi/utils/chinese_to_pinyin/chinese_to_pinyin.go

31 lines
643 B
Go
Raw Normal View History

2023-11-16 08:57:29 +00:00
package chinese_to_pinyin
import (
"github.com/mozillazg/go-pinyin"
"strings"
"unicode"
)
func ChineseToPinyin(str string) string {
p := pinyin.NewArgs()
p.Style = pinyin.Normal
finalStr := strings.Builder{}
for _, v := range str {
//判断是不是汉字
if isChineseCharacter(v) {
result := pinyin.Pinyin(strings.ToLower(string(v)), p)
r := strings.Builder{}
for _, v := range result {
r.WriteString(v[0])
}
finalStr.WriteString(r.String())
} else {
finalStr.WriteString(string(v))
}
}
return finalStr.String()
}
func isChineseCharacter(c rune) bool {
return unicode.Is(unicode.Scripts["Han"], c)
}