Skip to content

Commit

Permalink
对主文件进行大改,同时优化demo
Browse files Browse the repository at this point in the history
README.md 修正go get链接有误
normal.go 删除无用部分,添加注释,最重要的是请求方法从GET变为POST
2个demos 修正一个问题,添加go.mod解决本地包引用问题

Signed-off-by: UlinoyaPed <ulinoyaped@gmail.com>
  • Loading branch information
UlinoyaPed committed Feb 1, 2024
1 parent 48bbdfc commit 54ae2dc
Show file tree
Hide file tree
Showing 10 changed files with 181 additions and 114 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
## 安装

```bash
go get github.com/UlinoyaPed/BaiduTranslate@v1.1
go get github.com/UlinoyaPed/BaiduTranslate@v1.0.2
```

## 使用
Expand Down Expand Up @@ -110,7 +110,7 @@ en
错误码:54000,错误信息:PARAM_FROM_TO_OR_Q_EMPTY
```

## 受支持的翻译语言
## 受支持的翻译语言(部分)

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

Expand Down
101 changes: 33 additions & 68 deletions demos/FileTranslate/FileTranslate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,29 @@ package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"

"translate/BaiduTranslate"

"github.com/dablelv/go-huge-util/file"
"github.com/UlinoyaPed/BaiduTranslate"
)

func init() {
now := time.Now()
file := "./" + now.Format("2006-01-02") + ".log" // 使用2006年1月2号15点04分
file := "./" + now.Format("2006-01-02") + ".log"
logFile, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
if err != nil {
log.Println(err.Error())
log.Fatal(err)
}
log.SetOutput(logFile) // 将文件设置为log输出的文件
log.SetOutput(logFile)
log.SetPrefix("[Translate]")
log.SetFlags(log.LstdFlags | log.Lshortfile)

return
}

func FindFile(dirname string, format string) ([]string, error) {
names, err := file.GetDirAllEntryPaths(dirname, true)
if err != nil {
log.Println(err.Error())
}
var result []string
ext := ""
for i := 0; i < len(names); i++ {
ext = path.Ext(names[i])
if ext == format {
result[i] = names[i]
}
}
return result, err
}

func main() {
// 打印欢迎消息
s := `如果您第一次使用,请在本目录下创建profile.txt,并填入您的AppID和SecretKey
一行一个,不加前后缀!
请填入正确的AppID和SecretKey,否则输出为空!
Expand All @@ -55,59 +35,50 @@ jXXEOXyXXXfXXXXXsXXX
`
fmt.Println(s)

deploy, err := os.OpenFile("profile.txt", os.O_RDONLY|os.O_CREATE, 0755)
// 读取配置文件中的AppID和SecretKey
deployData, err := ioutil.ReadFile("profile.txt")
if err != nil {
log.Println(err.Error())
log.Fatal(err)
}

d := bufio.NewReader(deploy)
appID, _ := d.ReadString('\n')
appID = strings.TrimSpace(appID)
secretKey, _ := d.ReadString('\n')
secretKey = strings.TrimSpace(secretKey)
deployLines := strings.Split(string(deployData), "\n")
appID := strings.TrimSpace(deployLines[0])
secretKey := strings.TrimSpace(deployLines[1])
btr := BaiduTranslate.BaiduInfo{AppID: appID, SecretKey: secretKey}

in, err := os.OpenFile("input.txt", os.O_RDONLY|os.O_CREATE, 0755)
// 读取输入文件内容
inputData, err := ioutil.ReadFile("input.txt")
if err != nil {
log.Println(err.Error())
log.Fatal(err)
}
// 创建 Reader
r := bufio.NewReader(in)
inputLines := strings.Split(string(inputData), "\n")

file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
// 打开输出文件
outputFile, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
fmt.Println(err.Error())
log.Fatal(err)
}
defer file.Close()
writer := bufio.NewWriter(file)
defer outputFile.Close()

writer := bufio.NewWriter(outputFile)

i := 0
n := 0
from := "en"
to := "zh"
for {
line, ierr := r.ReadString('\n')
line = strings.TrimSpace(line) // 去掉字符串首尾空白字符
if ierr != nil && ierr != io.EOF {
log.Println(err.Error())
}

i++

for i, line := range inputLines {
line = strings.TrimSpace(line)
if line == "" {
log.Printf("第%d行是空行", i)
log.Printf("第%d行是空行", i+1)
fmt.Println()

_, err = writer.WriteString("\n")
if err != nil {
log.Println(err.Error())
log.Fatal(err)
}

} else {
if n != 1 {
// 检测语言并切换翻译方向
lang := btr.Detect(line)
if lang.Err() != nil {
log.Println(lang.Err().Error())
log.Printf("第%d行出现错误,错误:%s", i+1, lang.Err().Error())
} else {
fmt.Printf("语言:%s\n", lang.Lang)
if lang.Lang == to {
Expand All @@ -118,32 +89,26 @@ jXXEOXyXXXfXXXXXsXXX
}
}

// 进行翻译
result := btr.NormalTr(line, from, to)
if result.Err() != nil {
log.Printf("第%d行出现错误,错误:%s", i, result.Err().Error())
log.Printf("第%d行出现错误,错误:%s", i+1, result.Err().Error())
_, err = writer.WriteString("\n")
} else {
fmt.Printf("%s\n", result.Dst)
log.Printf("第%d行翻译完成!", i)

log.Printf("第%d行翻译完成!", i+1)
_, err = writer.WriteString(result.Dst + "\n")
if err != nil {
log.Println(err.Error())
log.Fatal(err)
}
}

}

if ierr == io.EOF {
break
}

}

fmt.Println("---翻译已完成,按回车键退出---")
log.Println("---翻译已完成---")

// 刷新缓冲区并关闭写入器
writer.Flush()
BaiduTranslate.Input()
return
}
14 changes: 14 additions & 0 deletions demos/FileTranslate/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module FileTranslate

go 1.19

require (
github.com/dablelv/cyan v0.0.54
github.com/tidwall/gjson v1.17.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
)

require github.com/UlinoyaPed/BaiduTranslate v0.0.0

replace github.com/UlinoyaPed/BaiduTranslate => ../../
8 changes: 8 additions & 0 deletions demos/FileTranslate/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
github.com/dablelv/cyan v0.0.54 h1:LFMzt0gndYJFbSScw/kGeTvfVZkszds7HJDjKFu69Hk=
github.com/dablelv/cyan v0.0.54/go.mod h1:SyRS9eXKDIXKiTgQ3Qjs97FsMh2mPi9ndPRDkJqSR3g=
github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM=
github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
2 changes: 1 addition & 1 deletion demos/NormalTranslate/NormalTranslate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"os"
"strings"

"translate/BaiduTranslate"
"github.com/UlinoyaPed/BaiduTranslate"
)

func main() {
Expand Down
13 changes: 13 additions & 0 deletions demos/NormalTranslate/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module NormalTranslate

go 1.19

require (
github.com/tidwall/gjson v1.17.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
)

require github.com/UlinoyaPed/BaiduTranslate v0.0.0

replace github.com/UlinoyaPed/BaiduTranslate => ../../
6 changes: 6 additions & 0 deletions demos/NormalTranslate/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM=
github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/UlinoyaPed/BaiduTranslate

go 1.19
103 changes: 60 additions & 43 deletions normal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,71 +4,88 @@ import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"

"github.com/tidwall/gjson"
)

// NormalResult 包含翻译结果和错误信息的结构体
type NormalResult struct {
Dst string

errCode string
errMsg string
Dst string // 翻译结果
ErrCode string // 错误码
ErrMsg string // 错误信息
}

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

//合并字符串,计算sign
// NormalTr 执行普通翻译的方法
func (info *BaiduInfo) NormalTr(text, from, to string) NormalResult {
// 生成随机盐值
salt := Salt(10)
montage := BaiduInfo.AppID + Text + salt + BaiduInfo.SecretKey
ctx := md5.New()
ctx.Write([]byte(montage))
sign := hex.EncodeToString(ctx.Sum(nil))
// 构造待翻译的字符串,并计算签名
sign := generateSign(info.AppID, text, salt, info.SecretKey)

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

// 发送GET请求
resp, err := http.Get(urlstr)
// POST请求
method := "POST"
// 5秒超时
timeout := time.Duration(5 * time.Second)
client := &http.Client{
Timeout: timeout,
}
req, err := http.NewRequest(method, urlStr, nil)
if err != nil {
log.Println("HTTP GET出现错误!")
fmt.Println(err)
// return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// 发送请求
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
// return
}
defer res.Body.Close()

bodyJson := string(body)
var res NormalResult
res.errCode = gjson.Get(bodyJson, "error_code").String()
res.errMsg = gjson.Get(bodyJson, "error_msg").String()
if res.errCode == "" {
trans := gjson.Get(bodyJson, "trans_result").Array()[0]
res.Dst = trans.Get("dst").String()
// 解析返回数据
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
// return
}
return res
//fmt.Println(string(body))

bodyJSON := string(body)
var resp NormalResult
resp.ErrCode = gjson.Get(bodyJSON, "error_code").String()
resp.ErrMsg = gjson.Get(bodyJSON, "error_msg").String()
if resp.ErrCode == "" {
trans := gjson.Get(bodyJSON, "trans_result").Array()[0]
resp.Dst = trans.Get("dst").String()
}
return resp
}

func (j NormalResult) Err() error {
if j.errCode != "" {
err := errors.New("通用翻译错误,错误码:" + j.errCode + ",错误信息:" + j.errMsg)
// Err 返回翻译错误信息
func (result NormalResult) Err() error {
if result.ErrCode != "" {
err := errors.New("通用翻译错误,错误码:" + result.ErrCode + ",错误信息:" + result.ErrMsg)
return err
} else {
return nil
}
}

/*
// json解析
trans := gjson.Get(string(body), "trans_result").Array()[0]
result := trans.Get("dst").String()
errorCode := gjson.Get(string(body), "error_code").String()
errorMsg := gjson.Get(string(body), "error_msg").String()
if errorCode != "" {
err := errors.New("错误码:" + errorCode + ",错误信息:" + errorMsg)
return "", err
} else {
return result, nil
}
*/
// generateSign 根据给定的参数生成签名
func generateSign(appID, text, salt, secretKey string) string {
// 合并字符串,计算sign
montage := appID + text + salt + secretKey
hash := md5.New()
hash.Write([]byte(montage))
sign := hex.EncodeToString(hash.Sum(nil))
return sign
}
Loading

0 comments on commit 54ae2dc

Please sign in to comment.