Python格式化压缩后的JS文件的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python格式化压缩后的JS文件的方法。分享给大家供大家参考。具体分析如下:

该脚本可以把压缩后的js文件格式上进行些还原,当然不会百分百完美,暂不处理语法问题,只是为了方便阅读js代码

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程序设计有所帮助。

相关文章

Python多进程multiprocessing用法实例分析

本文实例讲述了Python多进程multiprocessing用法。分享给大家供大家参考,具体如下: mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核...

python-tkinter之按钮的使用,开关方法

python-tkinter之按钮的使用,开关方法

具体参考哪位大佬的,记不太清楚了。 直接上代码,大体逻辑是这样的。 # -*- coding:utf-8 -*- from tkinter import * root=Tk()...

Python打开文件,将list、numpy数组内容写入txt文件中的方法

python保存numpy数据: numpy.savetxt("result.txt", numpy_data); 保存list数据: file=open('data.txt'...

浅析AST抽象语法树及Python代码实现

在计算机科学中,抽象语法树(abstract syntax tree或者缩写为AST),或者语法树(syntax tree),是源代码的抽象语法结构的树状表现形式,这里特指编程语言的源代...

python 判断三个数字中的最大值实例代码

python 判断三个数字中的最大值,具体代码如下所示: #判断三个数中最大值 n1= int(input('please enter the firest number:')) n...