Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 826391
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T03:24:29+00:00 2026-05-15T03:24:29+00:00

I thought I’d put together a quick script to consolidate the CSS rules I

  • 0

I thought I’d put together a quick script to consolidate the CSS rules I have distributed across multiple CSS files, then I can minify it.

I’m new to Python but figured this would be a good exercise to try a new language. My main loop isn’t parsing the CSS as I thought it would.

I populate a list with selectors parsed from the CSS files to return the CSS rules in order. Later in the script, the list contains an element that is not found in the dictionary.

    for line in self.file.readlines():
      if self.hasSelector(line):
        selector = self.getSelector(line)
        if selector not in self.order:
          self.order.append(selector)
      elif selector and self.hasProperty(line):
        # rules.setdefault(selector,[]).append(self.getProperty(line))
        property = self.getProperty(line)
        properties = [] if selector not in rules else rules[selector]
        if property not in properties:
          properties.append(property)
        rules[selector] = properties
        # print "%s :: %s" % (selector, "".join(rules[selector]))
    return rules

Error encountered:

$ css-combine combined.css test1.css test2.css 
Traceback (most recent call last):
  File "css-combine", line 108, in <module>
    c.run(outfile, stylesheets)
  File "css-combine", line 64, in run
    [(selector, rules[selector]) for selector in parser.order],
KeyError: 'p'

Swap the inputs:

$ css-combine combined.css test2.css test1.css 
Traceback (most recent call last):
  File "css-combine", line 108, in <module>
    c.run(outfile, stylesheets)
  File "css-combine", line 64, in run
    [(selector, rules[selector]) for selector in parser.order],
KeyError: '#header_.title'

I’ve done some quirky things in the code like sub spaces for underscores in dictionary key names in case it was an issue – maybe this is a benign precaution? Depending on the order of the inputs, a different key cannot be found in the dictionary.

The script:

#!/usr/bin/env python

import optparse
import re

class CssParser:

  def __init__(self):
    self.file = False
    self.order = [] # store rules assignment order

  def parse(self, rules = {}):
    if self.file == False:
      raise IOError("No file to parse")

    selector = False
    for line in self.file.readlines():
      if self.hasSelector(line):
        selector = self.getSelector(line)
        if selector not in self.order:
          self.order.append(selector)
      elif selector and self.hasProperty(line):
        # rules.setdefault(selector,[]).append(self.getProperty(line))
        property = self.getProperty(line)
        properties = [] if selector not in rules else rules[selector]
        if property not in properties:
          properties.append(property)
        rules[selector] = properties
        # print "%s :: %s" % (selector, "".join(rules[selector]))
    return rules

  def hasSelector(self, line):
    return True if re.search("^([#a-z,\.:\s]+){", line) else False

  def getSelector(self, line):
    s = re.search("^([#a-z,:\.\s]+){", line).group(1)
    return "_".join(s.strip().split())

  def hasProperty(self, line):
    return True if re.search("^\s?[a-z-]+:[^;]+;", line) else False

  def getProperty(self, line):
    return re.search("([a-z-]+:[^;]+;)", line).group(1)


class Consolidator:
  """Class to consolidate CSS rule attributes"""

  def run(self, outfile, files):
    parser = CssParser()
    rules = {}
    for file in files:
      try:
        parser.file = open(file)
        rules = parser.parse(rules)
      except IOError:
        print "Cannot read file: " + file
      finally:
        parser.file.close()

    self.serialize(
      [(selector, rules[selector]) for selector in parser.order],
      outfile
    )

  def serialize(self, rules, outfile):
    try:
      f = open(outfile, "w")
      for rule in rules:
        f.write(
          "%s {\n\t%s\n}\n\n" % (
            " ".join(rule[0].split("_")), "\n\t".join(rule[1])
          )
        )
    except IOError:
      print "Cannot write output to: " + outfile
    finally:
      f.close()

def init():
  op = optparse.OptionParser(
    usage="Usage: %prog [options] <output file> <stylesheet1> " +
      "<stylesheet2> ... <stylesheetN>",
    description="Combine CSS rules spread across multiple " +
      "stylesheets into a single file"
  )
  opts, args = op.parse_args()
  if len(args) < 3:
    if len(args) == 1:
      print "Error: No input files specified.\n"
    elif len(args) == 2:
      print "Error: One input file specified, nothing to combine.\n"
    op.print_help();
    exit(-1)

  return [opts, args]

if __name__ == '__main__':
  opts, args = init()
  outfile, stylesheets = [args[0], args[1:]]
  c = Consolidator()
  c.run(outfile, stylesheets)

Test CSS file 1:

body {
    background-color: #e7e7e7;
}

p {
    margin: 1em 0em;    
}

File 2:

body {
    font-size: 16px;
}

#header .title {
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 1.9em;
}

#header .title a, #header .title a:hover {
    color: #f5f5f5;
    border-bottom: none;
    text-shadow: 2px 2px 3px rgba(0, 0, 0, 1);
}

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T03:24:29+00:00Added an answer on May 15, 2026 at 3:24 am

    Change

    def hasProperty(self, line):
        return True if re.search("^\s?[a-z-]+:[^;]+;", line) else False
    

    to

    def hasProperty(self, line):
        return True if re.search("^\s*[a-z-]+:[^;]+;", line) else False
    

    The hasProperty was not matching anything because \s? matches only 0 or 1 whitespace character.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 450k
  • Answers 450k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The best is to keep the time in UTC. In… May 15, 2026 at 8:33 pm
  • Editorial Team
    Editorial Team added an answer The command line executable does convert 24-bit wavs correctly when… May 15, 2026 at 8:33 pm
  • Editorial Team
    Editorial Team added an answer microtime() returns the current time with microseconds. You will have… May 15, 2026 at 8:33 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.