Home  >  Article  >  Backend Development  >  Use go language and Baidu translation API to achieve Chinese-Danish translation

Use go language and Baidu translation API to achieve Chinese-Danish translation

WBOY
WBOYOriginal
2023-08-05 10:30:251246browse

Using Go language and Baidu Translation API to achieve Chinese-Danish translation

In today's global era, multilingual communication has become an indispensable ability. As people's understanding of and interest in cultures around the world increases, so does the need for cross-language text translation. This article will introduce how to use Go language and Baidu Translation API to achieve mutual translation between Chinese and Danish.

First, we need to register a Baidu developer account and create a translation API application. After obtaining the AppID and AppKey of the application, we can start writing Go language code.

First, we need to introduce the necessary packages into the Go language. Use the go get command to install the github.com/parnurzeal/gorequest package, which can facilitate us to send http requests.

package main

import (
    "fmt"
    "github.com/parnurzeal/gorequest"
    "log"
    "net/url"
    "strings"
)

Then, we defined a function Translate to implement the translation function. The function accepts the source language, the target language and the text to be translated as parameters and returns the translated result.

func Translate(from, to, text string) string {
    appID := "YOUR_APP_ID"
    appKey := "YOUR_APP_KEY"
    apiURL := "http://api.fanyi.baidu.com/api/trans/vip/translate"

    // 构造请求参数
    params := url.Values{}
    params.Set("q", text)
    params.Set("from", from)
    params.Set("to", to)
    params.Set("appid", appID)
    params.Set("salt", "123")

    // 计算sign
    sign := appID + text + "123" + appKey
    params.Set("sign", fmt.Sprintf("%x", md5.Sum([]byte(sign))))

    // 发送翻译请求
    request := gorequest.New()
    resp, body, errs := request.Get(apiURL).Query(params).End()

    if errs != nil {
        log.Fatal(errs)
    }

    if resp.StatusCode != http.StatusOK {
        log.Fatalf("Translation failed with status code: %d", resp.StatusCode)
    }

    // 解析返回结果
    type TranslationResult struct {
        TransResult []struct {
            Src  string `json:"src"`
            Dest string `json:"dst"`
        } `json:"trans_result"`
    }

    result := TranslationResult{}
    if err := json.Unmarshal([]byte(body), &result); err != nil {
        log.Fatal(err)
    }

    // 提取翻译结果
    var translation strings.Builder
    for _, trans := range result.TransResult {
        translation.WriteString(trans.Dest)
    }

    return translation.String()
}

Next, we can use the Translate function in the main function for testing.

func main() {
    from := "zh" // 中文
    to := "da" // 丹麦文
    text := "你好,世界!" // 待翻译文本

    translation := Translate(from, to, text)
    fmt.Printf("翻译结果:%s
", translation)
}

The above code implements a simple translation function from Chinese to Danish. You can change the values ​​of from, to and text according to your needs to achieve translation in other languages.

It should be noted that since Baidu Translation API has certain call restrictions, it is recommended to cache the translation results to avoid frequent calls to the API.

To sum up, this article introduces how to use Go language and Baidu Translation API to achieve mutual translation between Chinese and Danish. Through this example, you can also implement translation functions in other languages ​​based on similar methods. I hope this article will help you learn and use Go language and Baidu Translation API.

The above is the detailed content of Use go language and Baidu translation API to achieve Chinese-Danish translation. 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