Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...