前言
小朋宇,你有没有因为工具生成的log参差不齐而强迫症病发呢?不用担心,十一前我忍不了了之后呢,就决心把这个事情给他解决掉!
效果
首先是看下素材,原始文件是这样的,一个名为test的可怕文件:
================================
adddd | vvvvvvv | ddddddddssdsrsdfdslfkd99fi9 | 99oookmmmkjjj
1111111111| 23222222222 | ddddddddddddd | sssssssssssss
mnmnmnmnmnm | ccc | sssssssssddddddddddddddd | rrrrrrrrrrrrr
1|2|3|4
============8888888888888888888888888
qqqqqqqq|eeeeeeee|tttttttt|eeeeeeee
100 | 10000 | 1000000000 | 200000000000
ewe|dddddd|ssssss|1122223333
123 | 234 | 333
234|567| 555
345| 098|444
处理一下:
iPad:~/python_scr# ./align_log.py test
处理后的效果test.align.log:
================================
adddd | vvvvvvv | ddddddddssdsrsdfdslfkd99fi9 | 99oookmmmkjjj
1111111111 | 23222222222 | ddddddddddddd | sssssssssssss
mnmnmnmnmnm | ccc | sssssssssddddddddddddddd | rrrrrrrrrrrrr
1 | 2 | 3 | 4
============8888888888888888888888888
qqqqqqqq | eeeeeeee | tttttttt | eeeeeeee
100 | 10000 | 1000000000 | 200000000000
ewe | dddddd | ssssss | 1122223333
123 | 234 | 333
234 | 567 | 555
345 | 098 | 444
就说六不六哈哈哈,对齐使我快乐!
代码
话不多说,直接把代码贴上吧,毕竟在ipad上操作起来很不方便,老样子还是一行注释都没有,下次一定改一定改:
#!/usr/bin/python3
import sys
import os
import re
import argparse
def gen_align_log(tmp_line):
if len(tmp_line) == 0:
return tmp_line
hash = []
cnt = 1
out_line = []
for line in tmp_line:
i = 0
line = line.strip()
if len(hash) == 0:
cnt = line.count("|") + 1
for j in range(0, cnt):
hash.append(0)
for sub in line.split("|"):
sub = sub.strip()
hash[i] = max(len(sub), hash[i])
i = i + 1
for line in tmp_line:
i = 0
str = ""
for sub in line.split("|"):
sub = sub.strip()
str1 = "{:<%0d}" % hash[i]
if i == cnt - 1:
str = str + str1.format(sub)
out_line.append(str)
else:
str = str + str1.format(sub) + " | "
i = i + 1
return out_line
def main():
output_file = []
tmp_line = []
input_file = sys.argv[1]
with open (input_file, "r") as fl:
handle = fl.readlines()
pre_cnt = 0
for line in handle:
line = line.strip()
if line.count("|") > 1:
if len(tmp_line) == 0:
tmp_line.append(line)
pre_cnt = line.count("|")
elif line.count("|") == pre_cnt:
tmp_line.append(line)
else:
output_file.extend(gen_align_log(tmp_line))
tmp_line = []
tmp_line.append(line)
pre_cnt = line.count("|")
else:
output_file.extend(gen_align_log(tmp_line))
tmp_line = []
pre_cnt = 0
output_file.append(line)
if len(tmp_line) > 0:
output_file.extend(gen_align_log(tmp_line))
with open (input_file + ".align.log", "w") as fl:
for line in output_file:
fl.write(line + "\n")
if __name__ == '__main__':
main()