Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way to implement a css parser/replacer

Tags:

python

I want to implement a script that reads a CSS file and makes meaningful changes to it (adding/removing/replacing lines/words etc.). The basic logic is implement an RTL (right-to-left) transformation.

I could think of quite a few approaches to it:

  • file reader - read a line, analyze it and make the needed changes to it.
  • two phase scan - create in memory model, scan and change it, save model to text.
  • regular expressions - It might be quite difficult because some of them might be very complex.

basically what I'm wondering is which of those, or other methods, would be the python way to do it? are there any relevant libraries you think I should be familiar with for this kind of operation?

Edit: it's should be noted that this is a "learn python through this usable project" kind of project so I'm not familiar with most libraries you would mention here.

like image 477
arikg Avatar asked Jul 21 '12 12:07

arikg


1 Answers

If you want something "quick and dirty" there are many interesting ways to do this. (As you said: line-by-line, regular expressions, …)

But if you want to do it "right" (correct on all kinds of inputs) you’ll need a real parser based on the official CSS tokenization and grammar. In Python there is cssutils and tinycss. (Disclaimer: I’m tinycss’s author.) If you want to learn, I like to think that tinycss’s source code is straightforward and easy to learn :)

like image 79
Simon Sapin Avatar answered Sep 24 '22 08:09

Simon Sapin