考勤机数据处理

最近忙成🐶,毕设研究的主题是SDN,基于SDN控制器编写应用实现针对常见网络攻击的检测识别和过滤。相关成果和code应该会等到毕业论文验收后发出来,暂且只能一段空窗期了。

这是之前写的一个python程序,对多个考勤数据进行处理并生成Excel表格。由于年代久远。。不作详解了。code放在这里,以做记录。

pre-execute.sh

由于打卡机产生的数据是gb232编码的xml文件,python转码比较麻烦,所以这里使用iconv先转码,并做一些文件名的预处理。

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
#!/bin/bash
set -e
# convert encoding from gb2312 to utf-8
#iconv -f gb2312 -t utf-8 ~'20.*19.*' -o 2-19-utf8.xls
# sed -i 's/GB2312/utf-8/1' 2-19-utf8.xls
re_1='^(.*)11([aAbB])(.*).xls$' # match for 1ab
re_11='^(.*)11([cC])(.*).xls$' # match for 11c
re_111='^(.*)111([dD])(.*).xls$' # match for 111d
process()
{
outfile=${BASH_REMATCH[1]}$1${BASH_REMATCH[2]}${BASH_REMATCH[3]}.xml
iconv -f gb2312 -t utf-8 $2 -o $outfile
sed -i 's/GB2312/utf-8/1' $outfile
}
for i in `ls -1 .`;do
if [[ $i =~ $re_1 ]];then
process 1 $i
fi
if [[ $i =~ $re_11 ]];then
process 11 $i
fi
if [[ $i =~ $re_111 ]];then
process 111 $i
fi
done
echo -e 'Encoding done.\n Now process xml.'
python run.py *.xml
echo 'Clear temp file'
rm *.xml
echo 'Done'

run.py

python主程序。

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#coding=utf-8
#sudo pip install XlsxWriter
import re,copy,sys,string
import xlsxwriter
from datetime import date
try:
import xml.etree.cElementTree as et
except ImportError:
import xml.etree.ElementTree as et
# class MyXmlException(Exception):
# def __init__(self,err):
# Exception.__init__(self)
# self.err = err
# def __str__(self):
# if self.errno == 10:
# return "NameLocationError"
day_cycle = () #考勤天数和考勤周期
all_pre_column = 0 #固定信息所占列数
def get_day_length(sheet):
'''获得考勤周期'''
try:
table = sheet[0]
#whole table
row = table[3]
#row of '考勤周期'
cell = row[1]
#cell of '考勤周期'
data = cell[0]
#data of '考勤周期'
string = data.text
#string format
except Exception as e:
print '[Locate Date Error]:',e
exit(1)
try:
start_time,day_of_end = string.split('~')
year,day_of_start = start_time.split('/',1)
day_length = int(day_of_end.split('/')[1]) - int(day_of_start.split('/')[1])+1
month = day_of_end.split('/')[0]
if not 1 <= day_length <= 31:
print '[Date out of range]:',e
exit(2)
except Exception as e:
print '[Date Process Error]:',e
exit(3)
return day_length,string,int(year),int(month)
def get_max_and_min_time(time_seq):
'''处理时间序列,提取时间并筛选出最大值和最小值'''
if time_seq == None:
return None
else:
time_point = re.findall(r'.{5}',time_seq.text) #分割序列,提取hh:mm
max_time = max(time_point)
min_time = min(time_point)
return [min_time,max_time]
def print_dict(log):
'''简单显示字典中的内容'''
for entry in log:
print log[entry]['ID'],log[entry]['NAME']
print log[entry]['TIME']
print '=========\n'
def one_floor_process(xml_file):
'''处理一层楼的信息'''
try:
tree = et.parse(xml_file)
except Exception as e:
print e
exit(4)
try :
#root node
root = tree.getroot()
#sheet: '刷卡记录'
sheet = root[5]
table = sheet[0]
row_of_name = table[1]
row_of_cycle = table[3]
row_of_step = table[4]
except Exception as e:
print '[Check_log Locate Error]:',e
exit(5)
flag = 0 #flag位标记Name row和Time row.
dict_of_staff = {} #一层楼的所有信息存放在该字典中
global day_cycle
day_cycle = get_day_length(sheet)
day_length = day_cycle[0]
for row in table[5:]:
#考勤记录从table[5]的Row开始
if flag %2 ==0:
#对应xml文件中包含员工meta信息的Row
name_str = row[8][0].text
if name_str != u'\u59d3\u540d : ':
#'姓名'定位失败
print '[Name Locate Error]'
exit(6)
staff_id_str = row[2][0].text
staff_name_str = row[10][0].text
dict_of_one_staff = {} #存放一位员工的信息
dict_of_one_staff['NAME'] = staff_name_str
dict_of_one_staff['ID'] = staff_id_str
else:
#对应xml文件中包含员工打卡时间的Row
day_seq = 1 #日期
dict_of_month = {} #存放员工一个月的打卡时间
for cell in row:
#Day Cell
if day_seq <= day_length:
#xml中每个row默认cell都是31行,此处取当月实际天数
time_seq = cell.find('{urn:schemas-microsoft-com:office:spreadsheet}Data')
# find当前节点下是否有Data域(时间序列),如果没有则返回None
rtv_time = get_max_and_min_time(time_seq)
if rtv_time != None:
dict_of_month[day_seq] = rtv_time
else:
break
day_seq+=1
dict_of_one_staff['TIME'] = dict_of_month
dict_of_staff[ int(staff_id_str) ] = dict_of_one_staff
flag+=1
return dict_of_staff
def process_multi_floor():
'''处理多层楼信息'''
if len(sys.argv) == 1:
print 'Request file input'
exit(15)
file_list = sys.argv[1:]
total_list = [ one_floor_process(xml_file) for xml_file in file_list ]
len_of_id = [len(i) for i in total_list]
maxlen = max(len_of_id)
if len(set(len_of_id)) != 1:
print '[WARNNING]:各层楼员工数量不一致!'
for i in range(len(file_list)):
print file_list[i],len_of_id[i]
done_dict ={} #存放三层楼的所有信息
for floor in total_list: #每层楼
for staff in floor.keys(): #每个员工
if done_dict.has_key(staff) == False:
done_dict[staff] = copy.deepcopy(floor[staff]) #done_dict初始化
else:
time_dict_new = floor[staff]['TIME'] #待比较的time_dict
time_dict_base = done_dict[staff]['TIME'] #作为基准的time_dict
for day in time_dict_new: #每天
if time_dict_base.has_key(day):
# 筛选出最大值和最小值
if time_dict_new[day][0] < time_dict_base[day][0]: #min
time_dict_base[day][0] = time_dict_new[day][0]
if time_dict_new[day][1] > time_dict_base[day][1]: #max
time_dict_base[day][1] = time_dict_new[day][1]
else:
time_dict_base[day] = copy.deepcopy(time_dict_new[day])
return done_dict
def isweekend(day_cycle,day):
'''判断是否是周末'''
year = day_cycle[2]
month = day_cycle[3]
weekday = date(year,month,day).isoweekday()
if weekday - 6 >=0:
return True
else:
return False
def xlsx_format(workbook):
xl_format = {
'merge' : workbook.add_format({
'align':'center',
'valign':'vcenter',
}),
'title' : workbook.add_format({
'align':'center',
'valign':'vcenter',
'font_size':24,
'font_color':'#0099cc'
}),
'time' : workbook.add_format({
'align':'center',
'valign':'vcenter',
'font_size':9,
'num_format':'hh:mm AM/PM'
}),
'weekend' : workbook.add_format({
'align':'center',
'valign':'vcenter',
'font_size':9,
'num_format':'hh:mm AM/PM',
'bg_color':'#8585ad'
}),
'name' : workbook.add_format({
'align':'center',
'valign':'vcenter',
})
}
xl_format['name'].set_bold()
return xl_format
def get_column_id():
'''列坐标行,默认从A-AZ,共52行,如果不足需要手动添加'''
column_id = []
column_id.extend(string.ascii_uppercase)
extend_row = [ 'A'+i for i in string.ascii_uppercase ]
column_id.extend(extend_row)
return column_id
#
# def print_instance():
#
# title_ins = {
# 'text' : u'刷卡记录表',
# 'format' : xl_format['title'],
# 'start' : ,
# 'end':
# }
class Outprint(object):
"""docstring for """
def __init__(self,worksheet,argdict):
if argdict.has_key('str'):
self.print_str = argdict['str']
if argdict.has_key('format'):
self.xl_format = argdict['format']
if argdict.has_key('range'):
self.range = argdict['range']
if argdict.has_key('methord'):
self.methord = argdict['methord']
# if argdict.has_key['tack_up_column'] and argdict.has_key['base_column']:
# self.range =
#
self.worksheet = worksheet
def run(self):
if self.methord == 'merge':
self.worksheet.merge_range(self.range,self.print_str,self.xl_format)
if self.methord == 'write':
self.worksheet.write(self.range,self.print_str)
def more_info(workbook,worksheet,base_column):
column_id = get_column_id()
xl_format = xlsx_format(workbook)
arg_list = [
# print row of '打卡天数'
{
'str' : u'打卡天数',
'format' : xl_format['merge'],
'tack_up_column' : 1,
'methord': 'merge'
}
]
now = base_column
info_list = []
for i in arg_list:
i['range'] = column_id[now]+'4:'+column_id[now]+'5'
step = i['tack_up_column']
now += step
info_list.append(Outprint(worksheet,i))
return info_list
def print_basic(workbook,worksheet):
'''输出最基本的title栏
如果插入信息需要在该栏中插入相应的title'''
global day_cycle
day_length = day_cycle[0]
day_range = day_cycle[1]
column_id = get_column_id()
xl_format = xlsx_format(workbook)
base_column = 2 #id and name column
futher_column = len(more_info(workbook,worksheet,base_column))
global all_pre_column
all_pre_column = base_column + futher_column
title_column = column_id[day_length+all_pre_column]
title = Outprint(worksheet, #print title row of '刷卡记录表'
{
'str' : u'刷卡记录表',
'format' : xl_format['title'],
'range' : 'A1:'+title_column+'2',
'methord': 'merge'
})
title.run()
ch_zhouqi = Outprint(worksheet, #print chinese row of '考勤周期'
{
'str' : u'考勤周期:',
'range' : 'A3',
'methord' : 'write'
})
ch_zhouqi.run()
digit_zhouqi = Outprint(worksheet, #print value of '考勤周期'
{
'str' : day_range,
'format' : workbook.add_format({'align':'left'}),
'range' : 'B3:'+title_column+'3',
'methord': 'merge'
})
digit_zhouqi.run()
title_id = Outprint(worksheet, # print id row
{
'str' : 'ID',
'format' : xl_format['merge'],
'range' : 'A4:A5',
'methord': 'merge'
})
title_id.run()
title_name = Outprint(worksheet, # print name row
{
'str' : u'姓名',
'format' : xl_format['merge'],
'range' : 'B4:B5',
'methord': 'merge'
})
title_name.run()
more_list = more_info(workbook,worksheet,base_column)
for i in more_list:
i.run()
i = 0
for item in column_id[all_pre_column:day_length+all_pre_column]:
# 输出日期
i += 1
ran = item+'4'+':'+item+'5'
if isweekend(day_cycle,i):
worksheet.merge_range(ran,str(i),xl_format['weekend'])
else:
worksheet.merge_range(ran,str(i),xl_format['merge'])
def output_xlsx(done_dict):
'''将结果输出为excel文件'''
global day_cycle
day_length = day_cycle[0]
day_range = day_cycle[1]
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet = workbook.add_worksheet(u'刷卡统计表')
print_basic(workbook,worksheet)
column_id = get_column_id()
xl_format = xlsx_format(workbook)
time_cell_width = 5 #时间单元格的宽度
row = 6 # start row of staff info,fixed
for staff in done_dict:
column = 0
s_id = done_dict[staff]['ID']
s_name = done_dict[staff]['NAME']
s_time_dict = done_dict[staff]['TIME']
ran_of_id = column_id[column]+str(row)+':'+column_id[column]+str(row+1) #range of id,col='A'
column += 1
ran_of_name = column_id[column]+str(row)+':'+column_id[column]+str(row+1) #range of name,col='B'
column += 1
ran_of_fre = column_id[column]+str(row)+':'+column_id[column]+str(row+1)
column += 1
time_start = column
worksheet.merge_range(ran_of_id,s_id,xl_format['merge']) #print id
worksheet.merge_range(ran_of_name,s_name,xl_format['name']) #print name
worksheet.merge_range(ran_of_fre,len(s_time_dict),xl_format['merge']) #print frequency
global all_pre_column
column = all_pre_column
for day in range(1,day_length+1):
if s_time_dict.has_key(day):
row_min_time = column_id[column]+str(row)
row_max_time = column_id[column]+str(row+1)
min_time = s_time_dict[day][0]
max_time = s_time_dict[day][1]
worksheet.write(row_min_time,min_time)
worksheet.write(row_max_time,max_time)
column += 1
time_end = column
row += 2
worksheet.set_column(time_start,time_end,time_cell_width,xl_format['time'])
workbook.close()
done_dict = process_multi_floor()
#print done_dict
output_xlsx(done_dict)
如果您觉得这篇文章对您有帮助,不妨支持我一下!