Golang实现将中文转化为拼音

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Golang实现将中文转化为拼音

爷来辣   2023-02-03 我要评论

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

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

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

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

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
}
go get -u github.com/mozillazg/go-pinyin
go run main.go

结果图

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们