栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

从Python123学到的nodejs

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Python123学到的nodejs

为了更有效率地完成作业, 我决定干点儿什么.

经过一番操作我很容易就得到了测试样例的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); // 将json字符串转为js对象

let testcases = dataobj.data["18"]["testcases"];
let flag = false; // 标记 if 是否被输出

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]}:ntprint('${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 读写文件的APIJSON字符串的解析模板字符串的使用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/758033.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号