2014-02-09 31 views
-1

我有一個像一個CSS:蟒蛇如何解析CSS文件的鍵值

body, html { aaa: aaa } 
h1, h2 { bbb: bbb; } 
h3, h4, h5 { ccc: ccc; } 

,我想解析這個字符串,並得到一個有序的字典/或類似的東西:

{ 
    'body, html': 'aaa: aaa', 
    'h1, h2': 'bbb: bbb;', 
    'h3, h4, h5': 'ccc: ccc;' 
} 

我想知道所有的選擇及其屬性

有人知道了實現這一目標的任何Python庫?

謝謝!

+1

你有沒有嘗試[搜索](http://stackoverflow.com/search?q= [ python] css)之前問?甚至沒有[谷歌搜索](http://bit.ly/1dzplnF)呢? – Bakuriu

回答

1

我會建議使用cssutils模塊。

import cssutils 
from pprint import pprint 

css = u''' 
body, html { color: blue } 
h1, h2 { font-size: 1.5em; color: red} 
h3, h4, h5 { font-size: small; } 
''' 

dct = {} 
sheet = cssutils.parseString(css) 

for rule in sheet: 
    selector = rule.selectorText 
    styles = rule.style.cssText 
    dct[selector] = styles 


pprint(dct) 

輸出:

{u'body, html': u'color: blue', 
u'h1, h2': u'font-size: 1.5em;\ncolor: red', 
u'h3, h4, h5': u'font-size: small'} 

在你的問題,你問一個鍵/值表示。但是,如果你要訪問的individial選擇或根據企業的性質,使用rule.selectorList和遍歷其屬性爲rule.style

for property in rule.style: 
    name = property.name  
    value = property.value 
-1

如果你想擺脫;只是strip它試試這個

>>> a = [css for css in text.split("}\n") if css] 
>>> a 
['body, html { aaa: aaa ', 'h1, h2 { bbb: bbb; ', 'h3, h4, h5 { ccc: ccc; '] 
>>> {i.split("{")[0].strip():i.split("{")[1].strip() for i in a} 
{'h3, h4, h5': 'ccc: ccc;', 'body, html': 'aaa: aaa', 'h1, h2': 'bbb: bbb;'} 

+4

'.mypathologicalcase {content:「哦{廢話'; }' – Eric