通过 Hexo 程序生成的页面,其源代码会产生大量的空行,不仅影响排错,且会占用本地、网络资源。今天杜老师为大家分享一段 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
| #!/usr/bin/env python3 # coding: UTF-8 import re,os def minify_html(filename): with open(filename,'r',encoding='utf-8') as p: with open(filename+'.tmp','w',encoding='utf-8') as t: while True: l = p.readline() if not l: break else: if re.search('\S',l): t.write(l) os.remove(filename) os.rename(filename+'.tmp',filename) print('%s 已压缩!'%filename) def yasuo(dir_path): if dir_path[len(dir_path)-1] == '/': dir_path = dir_path[:len(dir_path)-1] file_list = os.listdir(dir_path) for i in file_list: if i.find('html') > 0: minify_html(dir_path+'/'+i) elif os.path.isdir(dir_path+'/'+i) and not re.match('\.|\_',i): yasuo("%s/%s"%(dir_path,i)) yasuo('/Hexo/public')
|
注意:请将脚本最后一行的/Hexo,修改为您 Hexo 的运行目录,并保存为.py 结尾的执行文件,每次 hexo g
后运行该脚本就行了!