What is the python way to implement parser / replace css

I want to implement a script that reads a CSS file and makes significant changes to it (add / remove / replace lines / words, etc.). The basic logic implements the RTL transform (from right to left).

I could come up with several approaches to it:

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

Basically, what interests me is which of these or other methods would be the python way to do this? Are there any relevant libraries that you think I should know for this kind of operation?

Edit: It should be noted that this is a “learn python through this useful project” project, so I am not familiar with most of the libraries that you mentioned here.

+3
source share
1 answer

If you need 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 this “correctly” (correctly on all inputs), you will need a real parser based on official CSS tokenization and grammar . Python has cssutils and tinycss . (Disclaimer: Im tinycsss.) If you want to learn, I like to think that the tinycsss source code is simple and straightforward :)

+9
source

All Articles