Home > Article > Backend Development > Implement Chinese-Arabic translation using go language and Baidu translation API
Using Go language and Baidu Translation API to implement Chinese-Arabic translation
Overview:
In the context of globalization, international exchanges are becoming more and more frequent, and translation tools have become very important. In the computer field, it is not complicated to use APIs to implement translation functions. This article will introduce how to use Go language and Baidu Translation API to achieve Chinese to Arabic translation.
package main import ( "fmt" "net/http" "io/ioutil" "encoding/json" ) func main() { // 百度翻译API密钥 appID := "your_app_id" secretKey := "your_secret_key" // 要翻译的文本 text := "你好,世界" // 构建API请求URL url := fmt.Sprintf("http://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=zh&to=ara&appid=%s&salt=123&sign=%s", text, appID, secretKey) // 发送GET请求 resp, err := http.Get(url) if err != nil { panic(err) } defer resp.Body.Close() // 读取响应内容 body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } // 解析JSON响应 var result map[string]interface{} json.Unmarshal(body, &result) // 提取翻译结果 translation := result["trans_result"].([]interface{})[0].(map[string]interface{})["dst"].(string) // 输出翻译结果 fmt.Println("翻译结果:", translation) }
translate.go
file. Make sure to replace your_app_id
and your_secret_key
with your actual Baidu Translate API key. Then, enter the directory where the file is located on the command line and execute the following command to compile and run the code: go run translate.go
Result analysis:
After the above code is executed, Output the following results:
翻译结果: مرحبا بك في العالم
It can be seen that the original Chinese text "Hello, world" was successfully translated into Arabic "مرحبا بك في العالم".
Summary:
This article shows how to use the Go language and Baidu Translation API to implement the Chinese to Arabic translation function. You can modify the code according to your needs to achieve translation between other languages. At the same time, Baidu Translation API also supports more parameters and functions. You can refer to the documentation (https://fanyi-api.baidu.com/doc/21) for more information.
The above is the detailed content of Implement Chinese-Arabic translation using go language and Baidu translation API. For more information, please follow other related articles on the PHP Chinese website!