SoFunction
Updated on 2025-03-10

Go language implements the function of converting Chinese into pinyin

There is a requirement: it is more troublesome to create a series of accounts for new users, and they plan to pass in names through the interface for initialization. Want to convert the name into pinyin. Because some accounts require both Chinese and English. Let’s take a look at how to solve it in Go.

To convert a user's name to a pinyin, you can use a third-party library in Go, such as /mozillazg/go-pinyin, a popular library specially used to convert Chinese characters to pinyin. You can generate English names in pinyin format through it, which are used for multilingual support when initializing your account.

step

Install go-pinyinlibrary.

Use the go-pinyin library to convert Chinese names to pinyin.

Generate the required pinyin formats (such as full pinyin, first letter of pinyin, etc.) according to the requirements.

Initialize the name through the API interface.

Implementation code example

Below is a simple example of a Go program that takes the user's name, converts it to pinyin, and then outputs the full pinyin and pinyin initials for use when the account is initialized.

1. Install the go-pinyin library

Run the following command in the project directory to install go-pinyin:

go get -u /mozillazg/go-pinyin

2. Write conversion code

Here is a sample program that uses the go-pinyin library to convert Chinese names to pinyin to generate the pinyin form of full spelling and initial letters.

package main

import (
	"fmt"
	"strings"

	"/mozillazg/go-pinyin"
)

// ConvertToPinyin Receive Chinese names and return full spelling and pinyin first lettersfunc ConvertToPinyin(name string) (fullPinyin, initials string) {
	// Use the default Chinese character conversion options	args := ()

	// Get a two-dimensional array of pinyin	py := (name, args)

	// Pinyin in the form of spelling and the first letter	var fullPinyinList []string
	var initialsList []string
	for _, syllable := range py {
		fullPinyinList = append(fullPinyinList, syllable[0])  // All pinyin		initialsList = append(initialsList, string(syllable[0][0]))  // First letter	}

	fullPinyin = (fullPinyinList, "")
	initials = (initialsList, "")

	return
}

func main() {
	name := "Zhang San"
	fullPinyin, initials := ConvertToPinyin(name)

	("Name:", name)
	("Full Pinyin:", fullPinyin)
	("Pinyin first letter:", initials)
}

3. Running example

After running the code, you will get the following output:

Name: Zhang San
All Pinyin: zhangsan
Pinyin initial letter: zs

Code description

The ConvertToPinyin function receives the Chinese name name and returns the full spelling and pinyin first letters.

The (name, args) function converts Chinese names into a two-dimensional array of pinyin, and the pinyin of each character will be stored as an array element.

fullPinyin is composed of the full pinyin of each character, while initials is composed of the first letter of the pinyin of each character.

Finally, splicing the pinyin fragments into a complete string format.

Integrate code into the API

The above code can be put into the API's processing function, receive the name as the request parameter, and return the converted pinyin.

Sample API Code

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"/mozillazg/go-pinyin"
)

type Response struct {
	FullPinyin string `json:"full_pinyin"`
	Initials   string `json:"initials"`
}

func convertToPinyin(name string) (string, string) {
	args := ()
	py := (name, args)

	var fullPinyinList, initialsList []string
	for _, syllable := range py {
		fullPinyinList = append(fullPinyinList, syllable[0])
		initialsList = append(initialsList, string(syllable[0][0]))
	}

	fullPinyin := (fullPinyinList, "")
	initials := (initialsList, "")

	return fullPinyin, initials
}

func handler(w , r *) {
	name := ().Get("name")
	if name == "" {
		(w, "Name is required", )
		return
	}

	fullPinyin, initials := convertToPinyin(name)
	response := Response{
		FullPinyin: fullPinyin,
		Initials:   initials,
	}

	().Set("Content-Type", "application/json")
	(w).Encode(response)
}

func main() {
	("/convert", handler)
	("Server is running at http://localhost:8080/")
	(":8080", nil)
}

Test API

Start the server and access:

http://localhost:8080/convert?name=Zhang San

Return result:

{
    "full_pinyin": "zhangsan",
    "initials": "zs"
}

Things to note

Accuracy of pinyin conversion: There may be subtle differences in different pronunciations during the conversion process, such as polyphonic characters. It is recommended to make adjustments based on specific circumstances in actual applications.

Internationalization support: For multilingual systems, consider whether other character sets and encoding formats need to be supported.

Error handling: If the user enters a non-Chinese name or contains special characters, checks and error handling can be added.

This is the article about the function of converting Chinese into pinyin in Go language. For more relevant content on Go Chinese to pinyin, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!