My cousin begged me to write a node script to convert the java error code table into excel and translate it into English

insert image description here

The java original code part is as follows

public static final int ERR_ONLINE_DECLINED             = 1025;    //交易联机拒绝
    //public static final int	ERR_RESELECT_APP			= 1026;	//GPO返回0x6985,重新选择应用
    public static final int ERR_OFFLINE_APPROVED            = 1027;    //交易脱机批准

The excel results that need to be obtained
insert image description here

Finally, node is used to cooperate with the above plug-ins to complete, and the relevant data in the java code is collected.

1. Install the plugin first

npm install node-xlsx
npm install line-reader
npm install http
npm install md5-node

2. Register an account on Baidu Translation API to receive free usage quota

https://ai.baidu.com/ai-doc/MT/ykqq95r2y

I originally planned to use Google, but recently I found that Google cannot be accessed. Anyone who knows can tell me.

After the registration application, you can get an appid and the corresponding secret key.

Normal use will return the translated result data as follows

{
	"from": "en",
	"to": "zh",
	"trans_result": [{
		"src": "apple",
		"dst": "\u82f9\u679c" //苹果
	}]
}

3. Then write the complete node code

//生成Excel依赖包
var xlsx = require('node-xlsx')
//写入文件依赖包
var fs = require('fs')
//一行一行读取
var lineReader = require('line-reader');
//网络请求
var http = require('http');
//md5加密
var md5 = require('md5-node');


var sheetList = []

var listCount = 0;

lineReaderTxt()


//将java文件代码的每一行读取
async function lineReaderTxt() {
	sheetList.push(['状态码', "状态值", "结果", "是否使用中", "代码行数来源"])
	var lineList = []
	var lineCount = 0
	lineReader.eachLine('PostCode.java', function(line, last) {
		lineCount += 1
		if (line.indexOf('//public static final int') != -1) {
			lineList.push(line)
		} else if (line.indexOf('public static final int') != -1) {
			lineList.push(line)
		}
		if (last) {
			console.log('最后一行了:', lineCount);
			const used = process.memoryUsage().heapUsed / 1024 / 1024;
			console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`);
			loopList(lineList)
		}
	});
}


function loopList(lineList) {
	var successCount = 0
	console.log("开始新的循环", lineList.length)
	var lineCount = 0
	lineList.forEach((line, index) => {
		if (line.indexOf('//public static final int') != -1) {
			lineCount += 1
			translateOneJavaLine(line, false, lineCount, index == (lineList.length - 1), (item) => {
				successCount += 1
				console.log("successCount1:" + successCount, "lineList:" + lineList.length)
			})
		} else if (line.indexOf('public static final int') != -1) {
			lineCount += 1
			translateOneJavaLine(line, true, lineCount, index == (lineList.length - 1), (item) => {
				successCount += 1
				console.log("successCount2:" + successCount, "lineList:" + lineList.length)
			})
		}
		if (successCount == lineList.length) {
			writeDataToExcel()
		}
	})
}


//讲数据写入excel
function writeDataToExcel() {
	console.log('写入excel前的校验', sheetList.length, listCount)
	//配置,设置列宽
	const options = {
		'!cols': [{
			wch: 30
		}, {
			wch: 10
		}, {
			wch: 50
		}, {
			wch: 20
		}, {
			wch: 20
		}]
	};
	//生成二进制数据流
	var buffer = xlsx.build([{
		name: "test",
		data: sheetList
	}], options);
	//写入文件
	fs.appendFile('./test13.xlsx', buffer, function(err) {
		if (err) {
			console.log(err, '保存excel出错')
		} else {
			console.log('写入excel成功!!!')
		}
	})
}

//提取并翻译一行的数据
function translateOneJavaLine(line, isUsed, lineNum, isLast, callback) {
	if (line.indexOf("=") != -1) {
		var itemList = []
		//校验是否有 = 符号
		var lis = line.split('=')
		const errorDaihao = lis[0].split('final int')[1].replace(/(^\s*)|(\s*$)/g, "")
		// console.log('输出的状态', errorDaihao)
		itemList.push(errorDaihao)
		const second = lis[1]
		const errorCode = second.split(';')[0].replace(/(^\s*)|(\s*$)/g, "")
		// console.log('输出的状态码', errorCode)
		itemList.push(errorCode)
		const seconds = lis[1].split(';')
		if (seconds.length > 1) {
			if (seconds[1].indexOf('//') != -1) {
				const translateSrc = seconds[1].split('//')[1].replace(/(^\s*)|(\s*$)/g, "")
				itemList.push(`${translateSrc}`)
				itemList.push(isUsed ? '是' : '否')
				itemList.push(`${lineNum}`)
				sheetList.push(itemList)
				callback(itemList)
			} else {
				itemList.push('nothing')
				itemList.push(isUsed ? '是' : '否')
				itemList.push(`${lineNum}`)
				sheetList.push(itemList)
				callback(itemList)
			}
		}
	}
}


//将中文翻译成引文 使用百度api
async function translateChineseToEnglish(keyword1) {
	var keyword = encodeURI(keyword1)
	// console.log('需要查询的数据', keyword)
	const appid = '20111008000339947'
	const secretKey = 'FGsDn1G62CdqyWVyFXQm'
	const randomStr = '1435660288'
	var params1 = `${appid}${keyword1}${randomStr}${secretKey}`
	var params2 = md5(params1)
	const baiduHost = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
	let url =
		`${baiduHost}?q=${keyword}&from=zh&to=en&appid=${appid}&salt=${randomStr}&sign=${params2}`
	return new Promise((resolve) => {
		http.get(url, function(res) {
			res.setEncoding('utf8');
			var body = "";
			res.on('data', function(chunk) {
				body += chunk;
			}).on('end', function() {
				var obj = JSON.parse(body)
				if (obj.trans_result && obj.trans_result.length > 0) {
					const result = obj.trans_result[0].dst
					// console.log('翻译的结果是', result)
					resolve(result)
				}
			});
		}).on('error', function(e) {
			console.log('请求报错', JSON.stringify(e))
		})
	})
}

4. Execute the node script and output excel

insert image description here

5. Finish the work and hand it over to my cousin

Guess you like

Origin blog.csdn.net/admin_jalen/article/details/127560541