一、背景
因为拿现有系统套新的系统,老系统词库里有很多单词描述为空,sql导出所有的描述为空的单词,利用翻译软件查询出对应的描述。
二、步骤
1、把导出来的单词按照一定的格式放在文档中。
2、注册百度的翻译平台(百度翻译开放平台),拿到appId和密钥。
3、编写Java代码解析文件,调用第三方的api接口。
三、示例
引入了fastJson和hutool的maven包
单词格式如下:
代码如下:
package com.niusensen.springbootmybatis;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author wangpf
* @version 1.0
* @date 2023/7/26 15:24
*/
public class Test {
public static void main(String[] args) throws Exception{
String appId = "2023xxxxxx";
String key="O5sSxxxxxxxcI";
String url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
BufferedReader reader = new BufferedReader(new FileReader("D:\\123.txt"));
String line = reader.readLine();
while(line != null){
List<String> strings = Arrays.asList(line.split( ","));
for(String str: strings){
try{
String param=str.replace("'", "");
String salt= cn.hutool.core.lang.UUID.fastUUID().toString();
String sign= SecureUtil.md5(appId+param+salt+key);
String strurl ="q="+param+"&from=en&to=zh&appid="+appId+"&salt="+ salt+"&sign="+sign;
String getResult= HttpUtil.createGet(url+strurl).execute().charset("utf-8").body();
Map<String,Object> maps = JSONObject.parseObject(getResult, Map.class);
List<Map> list = JSONArray.parseArray(JSON.toJSONString(maps.get("trans_result")),Map.class);
System.out.println("update xxxx_xx_xx ldw set ldw.word_desc = '"+list.get(0).get("dst")+"' where ldw.word_name = '"+param+"';");
Thread.sleep(1000);//因为免费的接口有一秒限制
}catch(Exception e) {
System.out.println("str="+str+",Exception"+e);
}
}
line = reader.readLine();
}
reader.close();
}
}