为了更有效率地完成作业, 我决定干点儿什么.
经过一番操作我很容易就得到了测试样例的json(javascript object notation)文件.
数据结构如下:
于是我想到了JS有现成的解析JSON的API,又因为nodejs有读写本地文件的权限,于是我选择了nodejs开搞.
搞事流程:
- 读入得到的json文件;
- 将json字符串对象化;
- 分析要输出的问题的代码的测试样例的数据结果;
- 根据样例数据结构编写输出到文件的代码模板;
- 遍历测试样例添加结果代码;
- 将Python代码写入文件;
- 搞完收工.
代码:
const fs = require('fs');
let datastr, dataobj;
let res = "";
datastr = fs.readFileSync("./data.json", 'utf8');
dataobj = JSON.parse(datastr);
let testcases = dataobj.data["18"]["testcases"];
let flag = false;
for (let key in testcases) {
input = testcases[key].input;
output = testcases[key].output;
input = input.split('\n');
let tpl = `if salary == ${input[0]} and five_one_insurance_fund == ${input[1]}:\n\tprint('${output}')\n`;
if (flag == true)
tpl = 'el' + tpl;
flag = true;
res = res + tpl;
}
try {
fs.writeFileSync('./out.py', res);
} catch (err) {
console.error(err);
}
结果代码:
if salary == 5400 and five_one_insurance_fund == 412:
print('应缴税款0.00元,实发工资4988.00元。')
elif salary == 8800 and five_one_insurance_fund == 1200:
print('应缴税款78.00元,实发工资7522.00元。')
elif salary == 6654.3 and five_one_insurance_fund == 421.9:
print('应缴税款81.97元,实发工资6150.43元。')
elif salary == -200 and five_one_insurance_fund == 200:
print('error')
elif salary == 8210 and five_one_insurance_fund == 210:
print('应缴税款90.00元,实发工资7910.00元。')
elif salary == 20000 and five_one_insurance_fund == 1200:
print('应缴税款1350.00元,实发工资17450.00元。')
elif salary == 33000 and five_one_insurance_fund == 2400:
print('应缴税款3740.00元,实发工资26860.00元。')
elif salary == 1000000 and five_one_insurance_fund == 1:
print('应缴税款432589.55元,实发工资567409.45元。')
elif salary == 88888 and five_one_insurance_fund == 4300:
print('应缴税款20695.80元,实发工资63892.20元。')
最后将我复习到的一些东西做个总结:
- node.js 读写文件的API
- JSON字符串的解析
- 模板字符串的使用
|