Skip to content

Commit

Permalink
重做翻译函数
Browse files Browse the repository at this point in the history
加入url encode,(应该)不会出现错误
Signed-off-by: UlinoyaPed <[email protected]>
  • Loading branch information
UlinoyaPed committed Dec 30, 2022
1 parent 37b4987 commit 2c8b5aa
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 115 deletions.
29 changes: 28 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,28 @@
.idea
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

#releases
releases/*
*.syso

#build
!go-winres.exe
!buildcross.bat
!winres/*

#other
*.log
*.bk
36 changes: 14 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,31 @@ go install github.com/UlinoyaPed/BaiduTranslate

## 使用

BaiduInfo结构体记录配置项,Salt为数据传送时加盐(库中已有函数实现,可直接调用),From项为翻译源语言(auto自动识别),To项为译文语言

```golang
```go
package main

import (
"fmt"

"github.com/UlinoyaPed/BaiduTranslate"
)

func main() {
bi := BaiduTranslate.BaiduInfo{AppID:"XXXXX",Salt:BaiduTranslate.Salt(5),SecretKey:"XXXXX",From:"auto",To:"en"}

bi.Text = "你好,世界"
fmt.Println(bi.Translate())
/*
bi.To = "wyw" //文言文
fmt.Println(bi.Translate())
bi.To = "jp" //日本语
fmt.Println(bi.Translate())
bi.To = "kor" //韩语
fmt.Println(bi.Translate())
bi.To = "fra" //法语
fmt.Println(bi.Translate())
bi.To = "de" //德语
fmt.Println(bi.Translate())
bi.To = "ru" //俄语
fmt.Println(bi.Translate())
*/
//输入基本信息,Salt长度无要求
// BaiduInfo结构体记录配置项,Salt为数据传送时加盐(库中已有函数实现,可直接调用)
btr := BaiduTranslate.BaiduInfo{AppID: "", Salt: BaiduTranslate.Salt(5), SecretKey: ""}

// 通用翻译
// 传入:(原文, 原文语言, 译文语言)
fmt.Println(btr.NormalTr("Hello world!", "en", "zh"))
fmt.Println(btr.NormalTr("百度翻译", "auto", "de"))
}

```

受支持的翻译语言(源语言语种不确定时可设置为 auto,目标语言语种不可设置为 auto)
## 受支持的翻译语言

**(源语言语种不确定时可设置为 auto,目标语言语种不可设置为 auto)**

| 语言简写 | 名称 |
| :------: | :----------: |
Expand Down
35 changes: 35 additions & 0 deletions base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package BaiduTranslate

import (
"log"
"math/rand"
"time"
)

// 百度翻译开放平台信息
type BaiduInfo struct {
AppID string
Salt string
SecretKey string
}

// 自动生盐
// 入口参数为盐的长度
func Salt(l int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}

// 错误检测,如果有错误输出msg
func checkErr(e error, msg string) {
if e != nil {
log.Println(msg)
}
return
}
113 changes: 113 additions & 0 deletions normal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package BaiduTranslate

import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
)

func (BaiduInfo *BaiduInfo) NormalTr(Text string, From string, To string) string {

type TransResult struct {
From string `json:"from"`
To string `json:"to"`
Result [1]struct {
Src string `json:"src"`
Dst string `json:"dst"`
} `json:"trans_result"`
ErrorCode string `json:"error_code"`
ErrorMsg string `json:"error_msg"`
}

//合并字符串,计算sign
montage := BaiduInfo.AppID + Text + BaiduInfo.Salt + BaiduInfo.SecretKey
ctx := md5.New()
ctx.Write([]byte(montage))
sign := hex.EncodeToString(ctx.Sum(nil))

// 翻译 传入需要翻译的语句
urlstr := "http://fanyi-api.baidu.com/api/trans/vip/translate?q=" + url.QueryEscape(Text) + "&from=" + From + "&to=" + To + "&appid=" + BaiduInfo.AppID + "&salt=" + BaiduInfo.Salt + "&sign=" + sign

// 发送GET请求
resp, err := http.Get(urlstr)
checkErr(err, "HTTP GET出现错误!")
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

var ts TransResult
_ = json.Unmarshal(body, &ts)
if ts.ErrorCode != "" {
errmsg := "错误码:" + ts.ErrorCode + ",错误信息:" + ts.ErrorMsg
return errmsg
} else {
return ts.Result[0].Dst
}
}

/*
// 返回结果
type TransResult struct {
From string `json:"from"`
To string `json:"to"`
Result [1]Result `json:"trans_result"`
ErrorCode string `json:"error_code"`
ErrorMsg string `json:"error_msg"`
Data [1]Data `json:"data"`
}
type Result struct {
Src string `json:"src"`
Dst string `json:"dst"`
}
type Data struct {
Src string `json:"src"`
}
// 生成32位MD5
func Sign(bi *BaiduInfo) string {
text := bi.AppID + bi.Text + bi.Salt + bi.SecretKey
ctx := md5.New()
ctx.Write([]byte(text))
return hex.EncodeToString(ctx.Sum(nil))
}
// 翻译 传入需要翻译的语句
func (bi *BaiduInfo) Translate() string {
url := "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + bi.Text + "&from=" + bi.From + "&to=" + bi.To + "&appid=" + bi.AppID + "&salt=" + bi.Salt + "&sign=" + Sign(bi)
resp, err := http.Get(url)
if err != nil {
log.Println("网络异常")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var ts TransResult
_ = json.Unmarshal(body, &ts)
if ts.ErrorCode != "" {
return ts.ErrorMsg
} else {
return ts.Result[0].Dst
}
}
func (bi *BaiduInfo) Detect() string {
url := "http://api.fanyi.baidu.com/api/trans/vip/language?q=" + bi.Text + "&appid=" + bi.AppID + "&salt=" + bi.Salt + "&sign=" + Sign(bi)
resp, err := http.Get(url)
if err != nil {
log.Println("网络异常")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var ts TransResult
_ = json.Unmarshal(body, &ts)
if ts.ErrorCode != "" {
return ts.ErrorCode
} else {
return ts.Data[0].Src
}
}
*/
75 changes: 0 additions & 75 deletions trans.go

This file was deleted.

17 changes: 0 additions & 17 deletions trans_test.go

This file was deleted.

0 comments on commit 2c8b5aa

Please sign in to comment.