python——代码制作数据表

vim  table.py
1
#!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 def get_length(ts): 4 ls = [] 5 hs = ts['head'] 6 for h in hs: 7 ls.append(len(h)) 8 bs = ts['body'] 9 for b in bs: 10 for i in range(len(ls)): 11 li = len(b[i]) 12 if ls[i] < li: 13 ls[i] = li 14 return ls 15 def out_line(ts): 16 rs = '+' 17 ls = get_length(ts) 18 for l in ls: 19 rs += '-'*(l+2)+'+' 20 rs += '\n' 21 return rs 22 23 def out_head(ts): 24 rs = '|' 25 ls = get_length(ts) 26 hs = ts['head'] 27 for i in range(len(ls)): 28 rs += ' '+hs[i]+' '*(ls[i]-len(hs[i]))+' |' 29 rs += '\n' 30 return rs 31 32 def out_body(ts): 33 rs = '' 34 ls = get_length(ts) 35 bs = ts['body'] 36 for i in bs: 37 r ='|' 38 for j in range(len(ls)): 39 r += ' '+i[j]+' '*(ls[j]-len(i[j]))+' |' 40 rs += r + '\n' 41 return rs 42 def out_table(ts): 43 rs = out_line(ts) 44 rs += out_head(ts) 45 rs += out_line(ts) 46 rs += out_body(ts) 47 rs += out_line(ts) 48 return rs 49 if __name__ == '__main__': 50 T = { 51 'head':[ 'User','Host', 'Password', 'tip'], 52 'body':[ 53 ['root','localhost', 'abc', ''], 54 ['andy','127.0.0.1', '1234567890', ''], 55 ['tim', '111.67.192.108', '', ''], 56 ] 57 } 58 print(out_table(T),end='')


执行结果:
+------+----------------+------------+-----+
| User | Host           | Password   | tip |
+------+----------------+------------+-----+
| root | localhost      | abc        |     |
| andy | 127.0.0.1      | 1234567890 |     |
| tim  | 111.67.192.108 |            |     |
+------+----------------+------------+-----+


 

调用上边的表模块,制作属于自己的数据表
vim biao.py
1
#!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import table 4 5 ts = { 6 'head': ['.jpg', '.png', '.gif'], 7 'body': [ 8 ['abc.jpg', 'xyz.png', 'xxx.gif'], 9 ['abc.jpg', 'xyz.png', 'xxx.gif'], 10 ['abc.jpg', 'xyz.png', 'xxx.gif'], 11 ] 12 } 13 14 rs = table.out_table(ts) 15 print(rs)

执行结果:
+---------+---------+---------+
| .jpg    | .png    | .gif    |
+---------+---------+---------+
| abc.jpg | xyz.png | xxx.gif |
| abc.jpg | xyz.png | xxx.gif |
| abc.jpg | xyz.png | xxx.gif |
+---------+---------+---------+

 

posted @ 2018-05-27 15:56  Leonardo-li  阅读(1041)  评论(0编辑  收藏  举报