Golang
主页 > 脚本 > Golang >

Golang实现将中文转化为拼音

2023-02-05 | 佚名 | 点击:

导语:新用户入职 创建一系列账号比较麻烦,打算通过接口传入姓名进行初始化。想把姓名转化成拼音。因为有些账号即需要中文也需要英文。

官方demo 参考了github.com/mozillazg/go-pinyin

搜到github.com/Chain-Zhang/pinyin的资料多一点,但貌似不维护了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

package main

 

import (

    "fmt"

    "github.com/mozillazg/go-pinyin"

)

 

func main() {

    hans := "中国人"

 

    // 默认

    a := pinyin.NewArgs()

    fmt.Println(pinyin.Pinyin(hans, a))

    // [[zhong] [guo] [ren]]

 

    // 包含声调

    a.Style = pinyin.Tone

    fmt.Println(pinyin.Pinyin(hans, a))

    // [[zhōng] [guó] [rén]]

 

    // 声调用数字表示

    a.Style = pinyin.Tone2

    fmt.Println(pinyin.Pinyin(hans, a))

    // [[zho1ng] [guo2] [re2n]]

 

    // 开启多音字模式

    a = pinyin.NewArgs()

    a.Heteronym = true

    fmt.Println(pinyin.Pinyin(hans, a))

    // [[zhong zhong] [guo] [ren]]

    a.Style = pinyin.Tone2

    fmt.Println(pinyin.Pinyin(hans, a))

    // [[zho1ng zho4ng] [guo2] [re2n]]

 

    fmt.Println(pinyin.LazyPinyin(hans, pinyin.NewArgs()))

    // [zhong guo ren]

 

    fmt.Println(pinyin.Convert(hans, nil))

    // [[zhong] [guo] [ren]]

 

    fmt.Println(pinyin.LazyConvert(hans, nil))

    // [zhong guo ren]

}

我想要的是后期把中文传入并转换成拼音 类似于用户名。

创建main.go

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

package main

 

import (

    "fmt"

    "github.com/mozillazg/go-pinyin"

    "strings"

    "reflect"

    "github.com/astaxie/beego"

)

 

func main() {

    hans := "中国人"

 

    a := pinyin.LazyConvert(hans, nil)

    // [zhong guo ren]

 

    var test []string = []string{}

    for a, v := range a{

        beego.Info(v)

        beego.Info(a)

        if a == 0 {

            test = append(test, v)

        } else {

            test = append(test, ",")

            test = append(test, v)

        }

 

    }

        beego.Info("处理1")

    beego.Info(test)

 

//  通过这一条处理 strings.Trim

    result := strings.Trim(fmt.Sprint(test), "[]")

    // result := strings.Replace(strings.Trim(fmt.Sprint(test), "[]"), " ", ",", -1)

    beego.Info(result)

    beego.Info(reflect.TypeOf(result))

 

result2 := strings.Replace(result, " , ", "", -1)

       beego.Info(result2)

    // zhongguoren

}

1

2

go get -u github.com/mozillazg/go-pinyin

go run main.go

结果图

原文链接:https://blog.csdn.net/xujiamin0022016/article/details/110367798
相关文章
最新更新