该条笔记由Elder在2023/3/27 21:37:12推送(百度翻译开发)
定义命令(package.json)
"activationEvents": [
"onCommand:translate.helloWorld"
]
设置contributes(package.json)
"contributes": {
"configuration": [
{
"title": "translateNamed",
"properties": {
"translate.appid": {
"type": "string",
"default": "20200122000377349",
"description": "百度翻译API-appid"
},
"translate.secret": {
"type": "string",
"default": "9foeYW5MUNeE1qgqIlAX",
"description": "百度翻译API-密钥"
}
}
}
],
"commands": [
{
"command": "translate.helloWorld",
"title": "Hello World"
}
]
}
写翻译api(新建translate-api.js)
const axios = require('axios');
const vscode = require('vscode');
const md5 = require('md5');
const appid = vscode.workspace.getConfiguration().get('translate.appid');
const secret = vscode.workspace.getConfiguration().get('translate.secret');
/**
*
* @param {string} q 查询语言
* @param {string} from 源语言
* @param {string} to 目标语言
*/
function translate(q,from,to){
var salt = Math.random();
return axios({
method: 'get',
url: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
params: {
q: q,
appid: appid,
from: from,
to: to,
salt: salt,
sign: md5(appid + q + salt + secret)
}
})
}
module.exports = {
translate
}
写activate(extension.js下)
const api = require('./translate-api');
function activate(context) {
let disposable = vscode.commands.registerCommand('translate.helloWorld', async function () {
let selectWord
// 获得选中的文本
const currentEditor = vscode.window.activeTextEditor
if (!currentEditor) return
const currentSelect = currentEditor.document.getText(currentEditor.selection)
if (!currentSelect) return
// 调用api
const data = await api.translate(currentSelect, 'zh', 'en')
if (data.data.error_code) {
vscode.window.showInformationMessage(data.data.error_code)
return
}
// 返回翻译结果
const result = data.data.trans_result[0].dst
// 基于空格分割
const list = result.split(' ')
// 如果翻译的文字个数大于1 ,选择下面其中一个格式
if (list.length > 1) {
const arr = []
// 小驼峰
arr.push(list.map((v, i) => {
if (i !== 0) {
return v.charAt(0).toLocaleUpperCase() + v.slice(1)
}
return v.toLocaleLowerCase()
}).join(''))
// - 号连接
arr.push(list.map(v => v.toLocaleLowerCase()).join('-'))
// 下划线连接
arr.push(list.map(v => v.toLocaleLowerCase()).join('_'))
// 大驼峰
arr.push(list.map(v => v.charAt(0).toLocaleUpperCase() + v.slice(1)).join(''))
selectWord = await vscode.window.showQuickPick(arr, { placeHolder: '请选择要替换的变量名' })
} else {
// 翻译的文字个数小于1
selectWord = list[0]
}
// 替换文本
if (selectWord) {
currentEditor.edit(editBuilder => {
editBuilder.replace(currentEditor.selection, selectWord)
})
}
});
context.subscriptions.push(disposable);
}
标签:baidu,const,vscode,list,api,appid,translate From: https://www.cnblogs.com/myfriend/p/translate-baidu-1bxv8l.html