通过正规表达式实现

'''

a regex-based JavaScript code compression kludge

'''

import re

class JSCompressor(object):

def __init__(self, compressionLevel=2, measureCompression=False):

'''

compressionLevel:

0 - no compression, script returned unchanged. For debugging only -

try if you suspect that compression compromises your script

1 - Strip comments and empty lines, don't change line breaks and indentation (code remains readable)

2 - Additionally strip insignificant whitespace (code will become quite unreadable)

measureCompression: append a comment stating the extent of compression

'''

self.compressionLevel = compressionLevel

self.measureCompression = measureCompression

# a bunch of regexes used in compression

# first, exempt string and regex literals from compression by transient substitution

findLiterals = re.compile(r'''

(\'.*?(?<=[^\\])\') | # single-quoted strings

(\".*?(?<=[^\\])\") | # double-quoted strings

((?

''', re.VERBOSE)

# literals are temporarily replaced by numbered placeholders

literalMarker = '@_@%d@_@' # temporary replacement

backSubst = re.compile('@_@(\d+)@_@') # put the string literals back in

mlc1 = re.compile(r'(\/\*.*?\*\/)') # /* ... */ comments on single line

mlc = re.compile(r'(\/\*.*?\*\/)', re.DOTALL) # real multiline comments

slc = re.compile('\/\/.*') # remove single line comments

collapseWs = re.compile('(?<=\S)[ \t]+') # collapse successive non-leading white space characters into one

squeeze = re.compile('''

\s+(?=[\}\]\)\:\&\|\=\;\,\.\+]) | # remove whitespace preceding control characters

(?<=[\{\[\(\:\&\|\=\;\,\.\+])\s+ | # ... or following such

[ \t]+(?=\W) | # remove spaces or tabs preceding non-word characters

(?<=\W)[ \t]+ # ... or following such

'''

, re.VERBOSE | re.DOTALL)

def compress(self, script):

'''

perform compression and return compressed script

'''

if self.compressionLevel == 0:

return script

lengthBefore = len(script)

# first, substitute string literals by placeholders to prevent the regexes messing with them

literals = []

def insertMarker(mo):

l = mo.group()

literals.append(l)

return self.literalMarker % (len(literals) - 1)

script = self.findLiterals.sub(insertMarker, script)

# now, to the literal-stripped carcass, apply some kludgy regexes for deflation...

script = self.slc.sub('', script) # strip single line comments

script = self.mlc1.sub(' ', script) # replace /* .. */ comments on single lines by space

script = self.mlc.sub('\n', script) # replace real multiline comments by newlines

# remove empty lines and trailing whitespace

script = '\n'.join([l.rstrip() for l in script.splitlines() if l.strip()])

if self.compressionLevel == 2: # squeeze out any dispensible whitespace

script = self.squeeze.sub('', script)

elif self.compressionLevel == 1: # only collapse multiple whitespace characters

script = self.collapseWs.sub(' ', script)

# now back-substitute the string and regex literals

def backsub(mo):

return literals[int(mo.group(1))]

script = self.backSubst.sub(backsub, script)

if self.measureCompression:

lengthAfter = float(len(script))

squeezedBy = int(100*(1-lengthAfter/lengthBefore))

script += '\n// squeezed out %s%%\n' % squeezedBy

return script

if __name__ == '__main__':

script = '''

/* this is a totally useless multiline comment, containing a silly "quoted string",

surrounded by several superfluous line breaks

*/

// and this is an equally important single line comment

sth = "this string contains 'quotes', a /regex/ and a // comment yet it will survive compression";

function wurst(){ // this is a great function

var hans = 33;

}

sthelse = 'and another useless string';

function hans(){ // another function

var bill = 66; // successive spaces will be collapsed into one;

var bob = 77 // this line break will be preserved b/c of lacking semicolon

var george = 88;

}

'''

for x in range(1,3):

print '\ncompression level', x, ':\n--------------'

c = JSCompressor(compressionLevel=x, measureCompression=True)

cpr = c.compress(script)

print cpr

print 'length', len(cpr)

标签:

isp

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

python压缩HTML文件,python压缩javascript文件代码相关推荐

  1. 如何在另一个JavaScript文件中包含一个JavaScript文件?

    JavaScript中是否有类似于CSS中@import的内容,可让您在另一个JavaScript文件中包含一个JavaScript文件? #1楼 而不是在运行时添加,而是使用脚本在上传之前进行串联. ...

  2. 利用python中的gzip模块压缩和解压数据流和文件

    直接给出源码实现, 分为两种情况: 1.网络连接中的数据流的压缩和解压,或是打开的文件读取一部分 2.打开文件压缩或是解压 #!/usr/bin/env python #encoding: utf-8 ...

  3. python压缩文件夹下的所有文件_python压缩文件夹内所有文件为zip文件的方法

    这里讨论使用Python解压如下五种压缩文件: .gz .tar .tgz .zip .rar 简介gz: 即gzip,通常只能压缩一个文件.与tar结合起来就可以实现先打包,再压缩. tar: li ...

  4. python编写的软件界面-用Python写一个带图形界面的文件压缩软件

    这又是一篇用Python写小软件系列,最近有点写上瘾了,文件压缩和解压我们在日常工作学习中会经常用到,比如winrar.快压.好压等压缩软件,猿人学用Python做个简易图形界面的压缩软件. 打开之后 ...

  5. python对文件进行压缩解压缩基于zip格式

    一.python压缩模块简介 python直接通过内置压缩模块可以直接进行压缩文件的创建: 内置模块 zipfile/rarfile 完成压缩文件的操作. 二. zipfile模块基础使用 2.1 对 ...

  6. Python自动解压各种压缩文件

    压缩文件是我们在使用电脑时经常会遇到的.压缩文件并不只有一种压缩模式.平常我们都是通过安装一些解压缩软件来打开这些不同的压缩文件.今天我们来谈一谈,如何用Python解压几种常见类型的压缩文件.    ...

  7. php 批量压缩png,利用Python批量压缩png方法实例(支持过滤个别文件与文件夹)...

    前言 本文主要给大家介绍的关于Python批量压缩png的相关资料,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: 1.需求 为什么会有这个需求?是因为游戏的资源大多是png图片,需要 ...

  8. Python下使用tarfile模块来实现文件归档压缩与解压

    Python下使用tarfile模块来实现文件归档压缩与解压   部分转自:http://www.diybl.com/course/3_program/python/20110510/555345.h ...

  9. Python文件夹压缩

    使用Python实现文件夹的压缩,做个记录,以备后查. #!/usr/bin/python # -*- coding:UTF-8 -*-import sys import os,os.path imp ...

  10. python压缩文件tar_python 实现tar文件压缩解压的实例详解

    python 实现tar文件压缩解压的实例详解 python 实现tar文件压缩解压的实例详解 压缩文件: import tarfile import os def tar(fname): t = t ...

最新文章

  1. Android开发中应避免的重大错误
  2. SpringBoot系列三:SpringBoot基本概念(统一父 pom 管理、SpringBoot 代码测试、启动注解分析、配置访问路径、使用内置对象、项目打包发布)...
  3. ★教师工资为什么这么低?/整理
  4. AS3.0开始类库依赖出现了四种新语法
  5. 黑龙江2020计算机一级考试时间,黑龙江2020年计算机等级考试报名时间汇总
  6. spring学习(48):自动装配中定义的bean的作用域
  7. Spring Boot 发送邮件
  8. C程序设计--排序(冒泡、选择、插入)--选择
  9. Java经典编程习题100例,供初学者学习
  10. 时间戳转换为年月日时分秒
  11. linux 下安装mantis
  12. Sqlmap全参数详解
  13. 计算机高程知识点,工程测量重点全部知识点(中国矿业大学)
  14. 8b/10b编码技术系列(二):Disparity、RD、8b/10b编码
  15. 安卓手机如何更改开机 关机 动画
  16. DPU网络开发SDK——DPDK(二)
  17. Wormhole流程搭建踩坑总结(一)
  18. IBM MB(IIB)访问数据库的消息流开发示例
  19. “办公自动化(OA)系统解决方案集”上线
  20. 你长得真帅,咱俩生个孩子吧

热门文章

  1. SPDY与http2
  2. android qq输入法,Android版QQ输入法:滑动输入成最大亮点
  3. 弹簧优化设计MATLAB,基于Matlab的圆柱螺旋弹簧可靠性优化设计
  4. 服务器上显示公式,Markdown中实时显示数学公式的方法
  5. 如何把map的value转为list_如何在Java中将Map转换为List?
  6. python信噪比signaltonoise, SNR
  7. FTP - YUM 源配置
  8. Spring实战第五版(中文版)学习笔记-第一章 Spring起步
  9. 【Advanced控制理论】Robust Control鲁棒控制(附Simulink程序)
  10. 修改版本名称及手机型号