package util import ( "bytes" "strings" "unicode" "github.com/mozillazg/go-pinyin" ) func PinyinFirstLetterUpper(hans string) string { if hans == "" { return "" } py := getPinyin(hans) return processPolyphones(hans, py) } func getPinyin(hans string) string { a := pinyin.NewArgs() a.Style = pinyin.FIRST_LETTER a.Heteronym = true pys := pinyin.Pinyin(hans, a) var buffer bytes.Buffer for _, py := range pys { buffer.WriteString(strings.ToUpper(py[0])) } return buffer.String() } var polyphoneDict = map[string][2]rune{ "阿": [2]rune{'A', 'E'}, "参": [2]rune{'C', 'S'}, "长": [2]rune{'C', 'Z'}, "术": [2]rune{'S', 'Z'}, } // 处理多音字,目前只支持一个汉字两个多音字的处理 func processPolyphones(src, py string) string { srcRune := []rune(src) keywordIndex := map[int][2]rune{} for i, r := range srcRune { if _, ok := polyphoneDict[string(r)]; ok { keywordIndex[i] = polyphoneDict[string(r)] } } if len(keywordIndex) == 0 { return py } pyRune := []rune(py) pyRuneReplaced := make([]rune, len(pyRune)) for i, r := range pyRune { pyRuneReplaced[i] = r if rs, ok := keywordIndex[i]; ok { for _, pr := range rs { if r != pr { pyRuneReplaced[i] = pr break } } } } if len(pyRuneReplaced) > 0 { pyRune = append(pyRune, ',') pyRune = append(pyRune, pyRuneReplaced...) } return string(pyRune) } //是否是字母字符串 func IsLetter(s string) bool { for _, r := range s { if !unicode.IsLetter(r) { return false } } return true }