Home  >  Article  >  Backend Development  >  Using go language and Baidu translation API to translate Chinese and Korean to each other

Using go language and Baidu translation API to translate Chinese and Korean to each other

王林
王林Original
2023-08-04 08:05:10753browse

Using Go language and Baidu Translation API to realize mutual translation between Chinese and Korean

Introduction

More and more people now need to communicate and cooperate across languages. This article will introduce how to use Go language and Baidu Translation API to achieve mutual translation between Chinese and Korean. Go language is a concise and efficient programming language, and Baidu Translation API is an interface that provides machine translation services. We will use Go language to write a simple program to achieve mutual translation between Chinese and Korean through Baidu Translation API.

Environment configuration

First, we need to apply for a developer account on the Baidu API open platform, create an application, and obtain the API's App ID and key. Next, we need to install the Go language development environment and use the go get command to install related dependency packages.

go get github.com/go-resty/resty/v2
go get golang.org/x/text/encoding/simplifiedchinese

Code implementation

The following is a code example of using Go language and Baidu translation API to translate Chinese and Korean to each other:

package main

import (
    "fmt"
    "io/ioutil"
    "net/url"
    "strings"

    "github.com/go-resty/resty/v2"
    "golang.org/x/text/encoding/simplifiedchinese"
)

const (
    appID     = "your_app_id"     // 请替换为你的应用App ID
    appSecret = "your_app_secret" // 请替换为你的应用密钥
    baseURL   = "https://fanyi-api.baidu.com/api/trans/vip/translate"
)

func main() {
    // 输入中文文本
    chineseText := "你好,世界!"
    // 中文翻译为韩文
    koreanText, err := translate(chineseText, "auto", "zh", "ko")
    if err != nil {
        fmt.Printf("翻译失败:%s
", err)
        return
    }
    fmt.Println("中文翻译为韩文:", koreanText)

    // 输入韩文文本
    koreanText = "안녕하세요, 세계!"
    // 韩文翻译为中文
    chineseText, err = translate(koreanText, "auto", "ko", "zh")
    if err != nil {
        fmt.Printf("翻译失败:%s
", err)
        return
    }
    fmt.Println("韩文翻译为中文:", chineseText)
}

func translate(text string, from, to, lang string) (string, error) {
    client := resty.New()
    // 使用URL编码对文本进行处理
    text = url.QueryEscape(text)
    // 拼接请求URL
    reqURL := fmt.Sprintf("%s?q=%s&from=%s&to=%s&appid=%s&salt=1", baseURL, text, from, to, appID)
    // 发送GET请求
    resp, err := client.R().Get(reqURL)
    if err != nil {
        return "", err
    }
    // 解析返回的JSON数据
    respData := struct {
        TransResult []struct {
            Src string `json:"src"`
            Dst string `json:"dst"`
        } `json:"trans_result"`
    }{}
    err = resp.Unmarshal(&respData)
    if err != nil {
        return "", err
    }
    // 提取翻译结果
    result := ""
    for _, tr := range respData.TransResult {
        result += tr.Dst
    }
    // 如果目标语言是中文,则解码
    if lang == "zh" {
        decoder := simplifiedchinese.GB18030.NewDecoder()
        decodedResult, err := decoder.String(result)
        if err != nil {
            return "", err
        }
        result = decodedResult
    }
    // 返回翻译结果
    return result, nil
}

In the above code, we first define Some constants, including the App ID, key and request URL of Baidu Translation API. Then, we defined a translate function to send HTTP requests and parse the returned JSON data. Finally, in the main function, we call the translate function to realize mutual translation between Chinese and Korean.

Running result output

When we run the program, the Chinese and Korean translation results will be output:

中文翻译为韩文: 안녕하세요, 세계!
韩文翻译为中文: 你好,世界!

Summary

This article introduces how to use the Go language Use Baidu Translation API to translate Chinese and Korean into each other. By using the HTTP client library of the Go language and the interface provided by Baidu Translation API, we can easily translate Chinese text into Korean and Korean text into Chinese. In actual projects, we can encapsulate and extend the code as needed to achieve more complex translation functions. Hope this article helps you!

The above is the detailed content of Using go language and Baidu translation API to translate Chinese and Korean to each other. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn