Home > Backend Development > Python Tutorial > Python格式化压缩后的JS文件的方法

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

WBOY
Release: 2016-06-06 11:21:56
Original
1739 people have browsed it

本文实例讲述了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))
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template