本文实例讲述了Python格式化压缩后的JS文件的方法。分享给大家供大家参考。具体分析如下:
该脚本可以把压缩后的js文件格式上进行些还原,当然不会百分百完美,暂不处理语法问题,只是为了方便阅读js代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | lines = open( "unformated.js" ).readlines()[0].split( ";" )
#一般压缩后的文件所有代码都在一行里
#视情况设定索引,我的情况时第0行是源代码。
indent = 0
formatted = []
for line in lines:
newline = []
for char in line:
newline.append(char)
if char== '{' : #{ 是缩进的依据
indent+=1
newline.append( "\n" )
newline.append( "\t" *indent)
if char== "}" :
indent-=1
newline.append( "\n" )
newline.append( "\t" *indent)
formatted.append( "\t" *indent+ "" .join(newline))
open( "formated.js" , "w" ).writelines( ";\n" .join(formatted))
|
登录后复制
希望本文所述对大家的Python程序设计有所帮助。