Go实现在线词典翻译(三种翻译接口,结合sync)

火山翻译

首先介绍用火山翻译英译汉。

package mainimport ("bufio""bytes""encoding/json""fmt""io""log""net/http""os""strings""unicode"
)type DictRequestHS struct {Source         string   `json:"source"`Words          []string `json:"words"`SourceLanguage string   `json:"source_language"`TargetLanguage string   `json:"target_language"`
}
type DictResponseHS struct {Details []struct {Detail string `json:"detail"`Extra  string `json:"extra"`} `json:"details"`
}type DictResponseHSData struct {Result []struct {Ec struct {Basic struct {Explains []struct {Pos   string `json:"pos"`Trans string `json:"trans"`} `json:"explains"`} `json:"basic"`} `json:"ec"`} `json:"result"`
}func query() {for {fmt.Println("请输入要查询的内容:")reader := bufio.NewReader(os.Stdin)word, _ := reader.ReadString('\n')word = strings.Trim(word, "\r\n")if IsEnglishString(word) {queryHS(word)break} else {fmt.Println("请输入英语")}}}
func queryHS(word string) {client := &http.Client{}request := DictRequestHS{"youdao", []string{word}, "en", "zh"}buf, err := json.Marshal(request)if err != nil {log.Fatal(err)}var data = bytes.NewReader(buf)req, err := http.NewRequest("POST", "https://translate.volcengine.com/web/dict/detail/v1/?msToken=&X-Bogus=DFSzswVOQDaibrQ3tJHN7cppgiFh&_signature=_02B4Z6wo00001g0lO6gAAIDD-FrRNX0w-.4NJT8AAOfuf7", data)if err != nil {log.Fatal(err)}req.Header.Set("authority", "translate.volcengine.com")req.Header.Set("accept", "application/json, text/plain, */*")req.Header.Set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")req.Header.Set("content-type", "application/json")req.Header.Set("cookie", "x-jupiter-uuid=16888064002651706; i18next=zh-CN; s_v_web_id=verify_ljtrq6kx_UW3ieIzP_8gQX_4abc_B8D8_AoHwuLysn026; ttcid=db98bce9149b4f09b905a71503d9331e36")req.Header.Set("origin", "https://translate.volcengine.com")req.Header.Set("referer", "https://translate.volcengine.com/?category=&home_language=zh&source_language=detect&target_language=zh&text=bad")req.Header.Set("sec-ch-ua", `"Not.A/Brand";v="8", "Chromium";v="114", "Microsoft Edge";v="114"`)req.Header.Set("sec-ch-ua-mobile", "?0")req.Header.Set("sec-ch-ua-platform", `"Windows"`)req.Header.Set("sec-fetch-dest", "empty")req.Header.Set("sec-fetch-mode", "cors")req.Header.Set("sec-fetch-site", "same-origin")req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43")resp, err := client.Do(req)if err != nil {log.Fatal(err)}defer resp.Body.Close()bodyText, err := io.ReadAll(resp.Body)if err != nil {log.Fatal(err)}if resp.StatusCode != 200 {log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))}var dictResponse DictResponseHSerr = json.Unmarshal(bodyText, &dictResponse)if err != nil {log.Fatal(err)}fmt.Println("火山翻译")item := dictResponse.Details[0]jsonStr := item.Detailvar HSData DictResponseHSDataerr = json.Unmarshal([]byte(jsonStr), &HSData)if err != nil {panic(err)}for _, item := range HSData.Result[0].Ec.Basic.Explains {fmt.Println(item.Pos, item.Trans)}
}func IsEnglishString(s string) bool {for _, r := range s {if unicode.IsLetter(r) && !unicode.Is(unicode.Scripts["Han"], r) {continue} else {return false}}return true
}func main() {defer func() {if msg := recover(); msg != nil {fmt.Println(msg, "输入不合法,请重新输入")}}()query()
}

请添加图片描述

彩云翻译和百度翻译

然后运用goroutine,结合sync包,同时实现彩云翻译和百度翻译。可对输入的内容自动检测,完成英译汉,汉译英。

package mainimport ("bufio""bytes""encoding/json""fmt""io""log""net/http""os""strings""sync"
)var wg sync.WaitGrouptype DictRequestCY struct {TransType string `json:"trans_type"`Source    string `json:"source"`UserID    string `json:"user_id"`
}type DictResponseCY struct {Rc   int `json:"rc"`Wiki struct {KnownInLaguages int `json:"known_in_laguages"`Description     struct {Source string      `json:"source"`Target interface{} `json:"target"`} `json:"description"`ID   string `json:"id"`Item struct {Source string `json:"source"`Target string `json:"target"`} `json:"item"`ImageURL  string `json:"image_url"`IsSubject string `json:"is_subject"`Sitelink  string `json:"sitelink"`} `json:"wiki"`Dictionary struct {Prons struct {EnUs string `json:"en-us"`En   string `json:"en"`} `json:"prons"`Explanations []string      `json:"explanations"`Synonym      []string      `json:"synonym"`Antonym      []string      `json:"antonym"`WqxExample   [][]string    `json:"wqx_example"`Entry        string        `json:"entry"`Type         string        `json:"type"`Related      []interface{} `json:"related"`Source       string        `json:"source"`} `json:"dictionary"`
}type DictResponseBD struct {Errno int `json:"errno"`Data  []struct {K string `json:"k"`V string `json:"v"`} `json:"data"`
}func queryBD(word string) {client := &http.Client{}var data = strings.NewReader("kw=" + word)req, err := http.NewRequest("POST", "https://fanyi.baidu.com/sug", data)if err != nil {log.Fatal(err)}req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")req.Header.Set("Connection", "keep-alive")req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")req.Header.Set("Cookie", "BIDUPSID=1CDF4C78BCFB3D90B2D6A594920DA6E4; PSTM=1630726121; __yjs_duid=1_02f9d28d226309370f287ee032114e3f1630763189674; REALTIME_TRANS_SWITCH=1; HISTORY_SWITCH=1; FANYI_WORD_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BAIDUID=396D4FB45E415311D3C31A0DE0D1AF80:FG=1; BDUSS=V6NWkyMzJnaTB-OWplSFdUR25tRkxsTzFnVnBDanN4ZEs2bHFMc2EzaXJOcDVrRVFBQUFBJCQAAAAAAAAAAAEAAACpaydUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKupdmSrqXZkMV; BDUSS_BFESS=V6NWkyMzJnaTB-OWplSFdUR25tRkxsTzFnVnBDanN4ZEs2bHFMc2EzaXJOcDVrRVFBQUFBJCQAAAAAAAAAAAEAAACpaydUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKupdmSrqXZkMV; APPGUIDE_10_6_2=1; MCITY=-75%3A; MAWEBCUID=web_jcjIPqwGUVRAlyJeYpGiILrRIWXcMWNDAjChgRXUZoHLpLyApr; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=1; BAIDUID_BFESS=396D4FB45E415311D3C31A0DE0D1AF80:FG=1; BA_HECTOR=2h852l8h2ha5840k8k0k050g1iai2fd1o; ZFY=kYWZ1Y6d6SV8cMcgDFNKAhwEEhlIK7W5gu1C:APN07HM:C; H_PS_PSSID=36546_39026_39022_38858_38957_38954_39009_38918_38972_38815_38637_26350_39041_38948_39046; ab_sr=1.0.1_MjBiYTAxMmUwMWE2MzIyODYxY2JiYzIxNjFjMWY2OTIwOTc5NTA1MTI5MzAzZGI2OWNiMGEwM2I1Y2IwNjJiZWEzNDQwOTg1ZTkyYTJkNmU1OTc3MjY1MTJhZTM1MGEwNWNlM2NkM2VjNWM0NDMwZjY0ZWJlZTEyOTQyZjFkZjE1YzhiYzY4YjBhYzQ4NzE2NWI4MjNkZjA1NTVkMDk2MmRjMjZhYTA4NThmOTYwMmEzOWMxMjAxMGM2OTdjODhm")req.Header.Set("Origin", "https://fanyi.baidu.com")req.Header.Set("Referer", "https://fanyi.baidu.com/")req.Header.Set("Sec-Fetch-Dest", "empty")req.Header.Set("Sec-Fetch-Mode", "cors")req.Header.Set("Sec-Fetch-Site", "same-origin")req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43")req.Header.Set("X-Requested-With", "XMLHttpRequest")req.Header.Set("sec-ch-ua", `"Not.A/Brand";v="8", "Chromium";v="114", "Microsoft Edge";v="114"`)req.Header.Set("sec-ch-ua-mobile", "?0")req.Header.Set("sec-ch-ua-platform", `"Windows"`)resp, err := client.Do(req)if err != nil {log.Fatal(err)}defer resp.Body.Close()bodyText, err := io.ReadAll(resp.Body)if err != nil {log.Fatal(err)}if resp.StatusCode != 200 {log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))}var dictResponse DictResponseBDerr = json.Unmarshal(bodyText, &dictResponse)if err != nil {log.Fatal(err)}fmt.Println("百度翻译")for _, item := range dictResponse.Data {fmt.Println(item.V)}wg.Done()}
func queryCY(word string) {client := &http.Client{}request := DictRequestCY{TransType: "en2zh", Source: word}buf, err := json.Marshal(request)if err != nil {log.Fatal(err)}var data = bytes.NewReader(buf)req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)if err != nil {log.Fatal(err)}req.Header.Set("Connection", "keep-alive")req.Header.Set("DNT", "1")req.Header.Set("os-version", "")req.Header.Set("sec-ch-ua-mobile", "?0")req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")req.Header.Set("app-name", "xy")req.Header.Set("Content-Type", "application/json;charset=UTF-8")req.Header.Set("Accept", "application/json, text/plain, */*")req.Header.Set("device-id", "")req.Header.Set("os-type", "web")req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")req.Header.Set("Origin", "https://fanyi.caiyunapp.com")req.Header.Set("Sec-Fetch-Site", "cross-site")req.Header.Set("Sec-Fetch-Mode", "cors")req.Header.Set("Sec-Fetch-Dest", "empty")req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")resp, err := client.Do(req)if err != nil {log.Fatal(err)}defer resp.Body.Close()bodyText, err := io.ReadAll(resp.Body)if err != nil {log.Fatal(err)}if resp.StatusCode != 200 {log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))}var dictResponse DictResponseCYerr = json.Unmarshal(bodyText, &dictResponse)if err != nil {log.Fatal(err)}fmt.Println("彩云翻译")fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)for _, item := range dictResponse.Dictionary.Explanations {fmt.Println(item)}wg.Done()
}func main() {fmt.Println("请输入要查询的内容:")reader := bufio.NewReader(os.Stdin)word, _ := reader.ReadString('\n')word = strings.Trim(word, "\r\n")wg.Add(2)go queryCY(word)go queryBD(word)wg.Wait()
}

请添加图片描述
请添加图片描述

工具推荐

1.json格式数据转golang结构体

JSON转Golang Struct - 在线工具 - OKTools

请添加图片描述

2.curl转爬虫代码

Convert curl commands to code (curlconverter.com)

请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/19801.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Ajax】笔记-Ajax案例准备与请求基本操作

案例准备HTML 按钮div <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>AJAX GET 请求</title&g…

线上后端接口响应过慢排查记录_MySQLthread cache命中率过低导致的接口响应慢

文章目录 问题现象初步排查调整临时解决措施问题二次定位原因分析为什么会出现异常 问题现象 9点多&#xff0c;运营同学反馈系统某模块业务响应很慢&#xff0c;登录系统查看&#xff0c;后端接口响应耗时很久&#xff0c;需要好几秒&#xff1b; 查看对应的服务器资源情况&a…

Django实现简单的音乐播放器 4

在原有音乐播放器功能基础上&#xff0c;增加上传音乐功能。 效果&#xff1a; 目录 配置上传路径 配置路由 视图处理歌曲 引入类库 保存歌曲文件 模板上传 设置菜单列表 设置菜单列表样式 脚本设置 上传效果 1.显示菜单列表 2.点击上传歌曲 3.上传完成 4.查看保…

SpringBoot前后端分离项目,打包、部署到服务器详细图文流程

文章目录 实施步骤一、修改配置文件地址1.修改MySQL配置2.修改Redis配置3.修改日志路径和字符集配置 二、将源码压缩并上传服务器1.上传前端文件2.上传后端文件&#xff08;同上&#xff09; 三、前端项目打包1.安装依赖2.项目打包 四、后端项目打包1.项目打包&#xff08;jar包…

一次零基础靶机渗透细节全程记录

一、打靶总流程 1.确定目标&#xff1a; 在本靶场中&#xff0c;确定目标就是使用nmap进行ip扫描&#xff0c;确定ip即为目标&#xff0c;只是针对此靶场而言。其他实战中确定目标的方式包括nmap进行扫描&#xff0c;但不局限于这个nmap。 2.信息收集&#xff1a; 比如平常挖…

【Matlab】智能优化算法_非洲秃鹫优化算法AVOA

【Matlab】智能优化算法_非洲秃鹫优化算法AVOA 1.背景介绍2.数学模型3.文件结构4.算法流程图5.伪代码6.详细代码及注释6.1 AVOA.m6.2 boundaryCheck.m6.3 exploitation.m6.4 exploration.m6.5 initialization.m6.6 levyFlight.m6.7 main.m6.8 ObjectiveFunction.m6.9 random_se…

前端处理后端返回的文件流,进行文件下载

二进制流格式 Blob格式 前言&#xff1a; 需求&#xff1a;根据后端接口返回的文件流进行数据处理&#xff0c;并实现文件的下载&#xff0c;且下载文件为word文档. 代码实现&#xff1a; //下载文件 async function DownLoadFile(row) {let res await DownLoadFileAPI(row.…

目标检测学习

目录 1、目标定位 2、特征点检测 3、目标检测 4、滑动窗口的卷积实现 5、Bounding Box 预测&#xff08;Bounding box predictions&#xff09; 6、交并化 7、非极大值抑制 8、Anchor Boxes 9、YOLO算法 1、目标定位 2、特征点检测 如何检测特征点&#xff08;以人的部…

【UE4 C++】根据指定路径生成静态网格体

在上一篇博客中&#xff08;【UE C】蓝图调用C函数&#xff09;&#xff0c;我们用C创建了一个蓝图函数库&#xff0c;本篇文章在这个蓝图函数库基础上增加一个方法&#xff0c;该方法只需输入一个文件目录路径&#xff0c;就可在场景中生成该目录下得所有静态网格体。&#xf…

ChatGPT对高校人才培养模式的挑战与应对策略思考

酷吗&#xff1f;输入指令后直接就能生成一大串代码&#xff0c;即使不懂相关技术也能玩转编程&#xff0c;这就是ChatGPT赋予你的“新能力”&#xff0c;除了写代码&#xff0c;ChatGPT还能帮你执行各种五花八门的任务。 AI工具如ChatGPT在行业中的广泛应用对于行业的人才结…

解密Sketch文件打开秘籍:简单两步操作!

虽然Figma&#xff0c;sketch,xd都很好用&#xff0c;但是设计师在设计工作流中经常会遇到无法在这三者软件中自由导入导出的情况。但是只要我们转变一下思路&#xff0c;因为这三种软件都支持导入sketch格式,所以我们只要将文件格式转成sketch&#xff0c;就能自由的在不同软件…

【华为鸿蒙3.0/荣耀安卓12使用VMOS Pro的激活方式】

关于华为鸿蒙3.0/荣耀安卓12如何解除进程限制&#xff0c;这里提供以下教程供小伙伴们参考。 需要准备&#xff1a;电脑一台&#xff0c;数据线一根。 第一步&#xff1a;打开手机USB调试模式。 确保USB数据线已连接手机和电脑&#xff0c;打开手机“开发者选项”&#xff0…