31 lines
643 B
Go
31 lines
643 B
Go
|
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)
|
||
|
}
|