Skip to content

Commit

Permalink
添加demo,对normal.go和detect.go做了较大修改(主要是json解析部分)
Browse files Browse the repository at this point in the history
  • Loading branch information
UlinoyaPed committed Jan 28, 2023
1 parent f3080cb commit 48bbdfc
Show file tree
Hide file tree
Showing 12 changed files with 539 additions and 39 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ releases/*
#other
*.log
*.bk
!*.off
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# golang的百度在线翻译库

该库用于调用百度翻译API,实现翻译效果。使用前,需要注册 [百度翻译开放平台信息](http://api.fanyi.baidu.com/api/trans/product/index)
该库用于调用百度翻译API实现翻译效果。使用前需要注册 [百度翻译开放平台信息](http://api.fanyi.baidu.com/api/trans/product/index)

## 安装

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

## 使用
Expand All @@ -18,7 +18,7 @@ package main
import (
"fmt"

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

func main() {
Expand Down Expand Up @@ -72,7 +72,7 @@ package main
import (
"fmt"

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

func main() {
Expand Down
9 changes: 9 additions & 0 deletions base.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package BaiduTranslate

import (
"bufio"
"math/rand"
"os"
"time"
)

Expand All @@ -23,3 +25,10 @@ func Salt(l int) string {
}
return string(result)
}

// 输入工具,可直接输入整行,不必为fmt.Scan的空格分词所困扰
func Input() string {
reader := bufio.NewReader(os.Stdin)
s, _ := reader.ReadString('\n')
return s
}
149 changes: 149 additions & 0 deletions demos/FileTranslate/FileTranslate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package main

import (
"bufio"
"fmt"
"io"
"log"
"os"
"path"
"strings"
"time"

"translate/BaiduTranslate"

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

func init() {
now := time.Now()
file := "./" + now.Format("2006-01-02") + ".log" // 使用2006年1月2号15点04分
logFile, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
if err != nil {
log.Println(err.Error())
}
log.SetOutput(logFile) // 将文件设置为log输出的文件
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,否则输出为空!
例:
20220517XXXX1XXXX
jXXEOXyXXXfXXXXXsXXX
`
fmt.Println(s)

deploy, err := os.OpenFile("profile.txt", os.O_RDONLY|os.O_CREATE, 0755)
if err != nil {
log.Println(err.Error())
}

d := bufio.NewReader(deploy)
appID, _ := d.ReadString('\n')
appID = strings.TrimSpace(appID)
secretKey, _ := d.ReadString('\n')
secretKey = strings.TrimSpace(secretKey)
btr := BaiduTranslate.BaiduInfo{AppID: appID, SecretKey: secretKey}

in, err := os.OpenFile("input.txt", os.O_RDONLY|os.O_CREATE, 0755)
if err != nil {
log.Println(err.Error())
}
// 创建 Reader
r := bufio.NewReader(in)

file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
fmt.Println(err.Error())
}
defer file.Close()
writer := bufio.NewWriter(file)

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++

if line == "" {
log.Printf("第%d行是空行", i)
fmt.Println()

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

} else {
if n != 1 {
lang := btr.Detect(line)
if lang.Err() != nil {
log.Println(lang.Err().Error())
} else {
fmt.Printf("语言:%s\n", lang.Lang)
if lang.Lang == to {
from, to = to, from
}
from = lang.Lang
n++
}
}

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

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

}

if ierr == io.EOF {
break
}

}

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

writer.Flush()
BaiduTranslate.Input()
return
}
1 change: 1 addition & 0 deletions demos/FileTranslate/input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
文化大革命如火如荼进行的同时,军方探寻外星文明的绝秘计划“红岸工程”取得了突破性进展。但在按下发射键的那一刻,历经劫难的叶文洁没有意识到,她彻底改变了人类的命运。地球文明向宇宙发出的第一声啼鸣,以太阳为中心,以光速向宇宙深处飞驰……四光年外,“三体文明”正苦苦挣扎——三颗无规则运行的太阳主导下的百余次毁灭与重生逼迫他们逃离母星。而恰在此时,他们接收到了地球发来的信息。在运用超技术锁死地球人的基础科学之后,三体人庞大的宇宙舰队开始向地球进发……人类的末日悄然来临。
2 changes: 2 additions & 0 deletions demos/FileTranslate/profile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
20220517XXXX1XXXX
jXXEOXyXXXfXXlXXsXXX
53 changes: 53 additions & 0 deletions demos/NormalTranslate/NormalTranslate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"bufio"
"fmt"
"os"
"strings"

"translate/BaiduTranslate"
)

func main() {

s := `如果您第一次使用,请在本目录下创建profile.txt,并填入您的AppID和SecretKey
一行一个,不加前后缀!
请填入正确的AppID和SecretKey,否则输出为空!
例:
20220517XXXX1XXXX
jXXEOXyXXXfXXlXXsXXX
CTRL+C退出
`
fmt.Println(s)

deploy, err := os.OpenFile("profile.txt", os.O_RDONLY|os.O_CREATE, 0755)
if err != nil {
fmt.Println(err.Error())
}

d := bufio.NewReader(deploy)
appID, _ := d.ReadString('\n')
appID = strings.TrimSpace(appID)
secretKey, _ := d.ReadString('\n')
secretKey = strings.TrimSpace(secretKey)
btr := BaiduTranslate.BaiduInfo{AppID: appID, SecretKey: secretKey}

for {
fmt.Printf(">")
q := BaiduTranslate.Input() // 从标准输入读取整行,请不要用fmt的Scanner
to := "zh"
lang := btr.Detect(q).Lang
if lang == to {
to = "en"
}
a1 := btr.NormalTr(q, "auto", to)
if a1.Err() != nil {
fmt.Println(a1.Err().Error())
} else {
fmt.Println(a1.Dst)
}
}

}
2 changes: 2 additions & 0 deletions demos/NormalTranslate/profile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
20220517XXXX1XXXX
jXXEOXyXXXfXXlXXsXXX
51 changes: 36 additions & 15 deletions detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@ package BaiduTranslate
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"net/url"

"github.com/tidwall/gjson"
)

func (BaiduInfo *BaiduInfo) Detect(Text string) (string, error) {
type DetectResult struct {
Lang string

type DetectResult struct {
Data struct {
Src string `json:"src"`
} `json:"data"`
ErrorCode string `json:"error_code"`
ErrorMsg string `json:"error_msg"`
}
errCode string
errMsg string
}

func (BaiduInfo *BaiduInfo) Detect(Text string) DetectResult {

//合并字符串,计算sign
salt := Salt(10)
Expand All @@ -36,16 +36,37 @@ func (BaiduInfo *BaiduInfo) Detect(Text string) (string, error) {
if err != nil {
log.Println("HTTP GET出现错误!")
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

var ts DetectResult
_ = json.Unmarshal(body, &ts)
// json解析
bodyJson := string(body)
var res DetectResult
res.errCode = gjson.Get(bodyJson, "error_code").String()
res.errMsg = gjson.Get(bodyJson, "error_msg").String()
if res.errCode == "0" {
res.Lang = gjson.Get(bodyJson, "data.src").String()
}

if ts.ErrorCode != "" {
err := errors.New("错误码:" + ts.ErrorCode + ",错误信息:" + ts.ErrorMsg)
return "", err
return res

}

func (j DetectResult) Err() error {
if j.errCode != "0" {
err := errors.New("语种识别错误,错误码:" + j.errCode + ",错误信息:" + j.errMsg)
return err
} else {
return ts.Data.Src, nil
return nil
}
}

/*
if errorCode != "0" {
err := errors.New("错误码:" + errorCode + ",错误信息:" + errorMsg)
return "", err
} else {
return result, nil
}
*/
Loading

0 comments on commit 48bbdfc

Please sign in to comment.