用于缩小CSS的Python脚本?

Wil*_*fat 43 css python compression minify

我正在寻找一个简单的Python脚本,可以将CSS缩小为网站部署过程的一部分.(Python是服务器上唯一支持的脚本语言,像CSS Utils这样的完整解析器对于这个项目来说太过分了).

基本上我喜欢CSS的jsmin.py.单个脚本没有依赖项.

有任何想法吗?

Bor*_*gar 67

这对我来说似乎是一个很好的任务,进入python,已经暂停了一段时间.我特此提出我的第一个python脚本:

import sys, re

with open( sys.argv[1] , 'r' ) as f:
    css = f.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] ) 
Run Code Online (Sandbox Code Playgroud)

我相信这可以工作,并在最近的Safari,Opera和Firefox上输出测试.它将打破除了下划线和/**/黑客之外的CSS黑客攻击!如果您正在进行大量黑客攻击(或将它们放在单独的文件中),请不要使用缩放器.

关于我的python的任何提示表示赞赏.请温柔,这是我的第一次.:-)

  • 您可以使用索引-1来引用序列中的最后一个元素。因此,您可以使用.append()而不是.insert(),并避免使用.reverse()。另外,如果len(lst)&gt; 0:通常就像lst: (2认同)
  • 感谢您的提示。我已经修复了这些问题和其他一些问题。Python 是一门非常好的语言。:-) (2认同)
  • 多年以后......仍然有用:)现在是我构建过程的一部分 (2认同)
  • @AtesGoral为什么会出现问题? (2认同)

Gre*_*ger 12

有一个YUI的CSS压缩器端口可用于python.

以下是PyPi上的项目页面:http://pypi.python.org/pypi/cssmin/0.1.1

  • **rCSSMin**是另一个端口,似乎维护:https://github.com/ndparker/rcssmin (2认同)