用于缩小CSS的Python脚本?

前端之家收集整理的这篇文章主要介绍了用于缩小CSS的Python脚本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一个简单的Python脚本,可以缩减CSS作为网站部署过程的一部分。 (Python是服务器上唯一支持的脚本语言,而像 CSS Utils这样的完整解析器对这个项目来说是过度的。

基本上我想jsmin.py为CSS。没有依赖关系的单个脚本。

有任何想法吗?

解决方法

这似乎是一个很好的任务,我进入python,这已经一段时间了。我现在介绍我的第一个python脚本:
import sys,re

css = open( sys.argv[1],'r' ).read()

# remove comments - this will break a lot of hacks :-P
css = re.sub( r'\s*/\*\s*\*/',"$$HACK1$$",css ) # preserve IE<6 comment hack
css = re.sub( r'/\*[\s\S]*?\*/',"",css )
css = css.replace( "$$HACK1$$",'/**/' ) # preserve IE<6 comment hack

# url() doesn't need quotes
css = re.sub( r'url\((["\'])([^)]*)\1\)',r'url(\2)',css )

# spaces may be safely collapsed as generated content will collapse them anyway
css = re.sub( r'\s+',' ',css )

# shorten collapsable colors: #aabbcc to #abc
css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)',r'#\1\2\3\4',css )

# fragment values can loose zeros
css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;',r':\1;',css )

for rule in re.findall( r'([^{]+){([^}]*)}',css ):

    # we don't need spaces around operators
    selectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])',r'',selector.strip() ) for selector in rule[0].split( ',' )]

    # order is important,but we still want to discard repetitions
    properties = {}
    porder = []
    for prop in re.findall( '(.*?):(.*?)(;|$)',rule[1] ):
        key = prop[0].strip().lower()
        if key not in porder: porder.append( key )
        properties[ key ] = prop[1].strip()

    # output rule if it contains any declarations
    if properties:
        print "%s{%s}" % ( ','.join( selectors ),''.join(['%s:%s;' % (key,properties[key]) for key in porder])[:-1] )

我相信这工作,并输出它测试罚款最近的Safari,Opera和Firefox。它会打破CSS黑客除了下划线& / ** / hacks!如果你有很多黑客(或将它们放在一个单独的文件),不要使用一个小工具。

任何提示我的python赞赏。请温柔,虽然,这是我第一次。 原文链接:https://www.f2er.com/css/222285.html

猜你在找的CSS相关文章