Home > Backend Development > Python Tutorial > Python脚本实现格式化css文件

Python脚本实现格式化css文件

WBOY
Release: 2016-06-10 15:16:00
Original
1101 people have browsed it

最近研究研究了css,少不了去网上分析一下别人的网页, 但很多网站的css文件都是要么写在一行,要么一个换行都没有,看起来极其痛苦,所以写一个脚本转换一下,转换为比较有可读性的格式。下面就是这个脚本:

import string, sys
import re, StringIO

TAB=4


def format(ss):
  f = open (ss, "r")
  data = f.read()
  f.close()
  
  dlen = len(data)
  i = 0
  buf = StringIO.StringIO()
  start = 0
  while i < dlen:
    if data[i] == '{':
      
      buf.write(data[start:i] + ' { ')
      i = i + 1
      start = i
    elif data[i] == '}':
      last = string.strip(data[start:i])
      if last:
        buf.write(' '*TAB + last + ';')
      buf.write(' } ')
      i = i + 1
      start = i
      
    elif data[i] == ';':
      line = string.strip(data[start:i])
      
      buf.write(' '*TAB + line + '; ')
      i = i + 1
      start = i
    
    else:
      i = i + 1
  buf.write(data[start:i+1])
  
  return buf.getvalue()
  
  
if __name__ == '__main__':
  if len(sys.argv) == 1:
    print 'usage: cssformat.py filename'
    sys.exit()
  
  ret = format(sys.argv[1])
  print ret

Copy after login

使用方法:

python cssformat.py  待转换的文件名 > 转换后保存的文件

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