python算工资

一直说了给妹子编个程序算工资,最近学完python基础,半天搞完基础版本

IPO分析

输入为txt文档,第一行为表头,之后每一行为一个员工人员信息。

1
2
3
4
5
6
7
8
name    munber  title   workday     base-money
zhang 001 master 21 2000
hui 002 employee 29 1000
huiz 002 employee 29 300
adfa 002 employee 29 123
吴波 002 master 29 2500
zfg 002 employee 29 322
pengke 002 employee 29 3000

处理过程分为三个功能函数,一个主函数。readfile读取输入文件,将文件内容转换为list,list的每一个项为一个字典,函数最后返回一个list。compute为计算函数,输入list,输出添加字典key的list。writefile函数将compute返回的list写入到文件,输入list、目标文件,无返回。
输出为txt文件,比输入文件多一列,total。

1
2
3
4
5
6
7
8
name    title    base-money    workday    total    munber    
zhang master 2000 21 4000.0 001
hui employee 1000 29 1500.0 002
huiz employee 300 29 450.0 002
adfa employee 123 29 184.5 002
吴波 master 2500 29 5000.0 002
zfg employee 322 29 483.0 002
pengke employee 3000 29 4500.0 002

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def readfile(filename):
inputList=[]
with open(filename) as f:
# print(f.read())
fileList = f.readlines()
person = {}
keylist = fileList[0].split()
for i in range(1,len(fileList)):
valuelist = fileList[i].split()
for j in range(len(keylist)):
person[keylist[j]] = valuelist[j]
inputList.append(person)
person = {}
f.close()
# print(inputList)
return inputList

def compute(inputList):
outputList = inputList[:]
for i in range(len(outputList)):
if outputList[i].get("title") == "master":
outputList[i]["total"] = float(outputList[i].get("base-money"))*2
else:
outputList[i]["total"] = float(outputList[i].get("base-money"))*1.5
#print(outputList)
return outputList

def writefile(outputList,outputfile):
title = (outputList[0].keys())[:]
with open(outputfile,"w") as f :
for i in range(len(title)):
f.write(title[i]+" ")
f.write("\n")
for j in range(len(outputList)):
f.write(outputList[j]["name"]+" "+outputList[j]["title"]+" "+outputList[j]["base-money"]+" "+outputList[j]["workday"]+" "+str(outputList[j]["total"])+" "+outputList[j]["munber"])
f.write("\n")
f.close
if __name__ == "__main__":
inputfile = "/home/hhzzer/PycharmProjects/gongzi/name.txt"
output = "./output.txt"
inputlist = readfile(inputfile)
outputlist = compute(inputlist)
outputfile = writefile(outputlist,output)

遇到问题及后续改善

问题

person字典未重置,导致输入list重复
22行缺少”)”,导致报错。
linux 换行符为”\n”,不需要转义。

改善

使用format字符串格式化文件写入行,对齐准确。