5 css python regex list python-3.x
我想将CSS文件的内容拆分为代码块,并使用Python 3.5将每个代码块压缩到一个列表中.
所以,鉴于这个CSS:
h1 {color: #333, background-color: transparent}
h2 {
font-weight:300
}
h3
{
font-weight: 200
}
Run Code Online (Sandbox Code Playgroud)
我们可以清楚地告诉它有多种样式和/或类型的缩进意味着CSS必须整理才能得到这个:
h1 {
color: #333,background-color: transparent;
}
h2 {
font-weight: 300;
}
h3 {
font-weight: 200;
}
Run Code Online (Sandbox Code Playgroud)
我如何使用Python来读取整齐的CSS字符串并将其中的每个代码块推送到Python列表中,如下所示:
styles = [
"h1 {\n color: #333,background-color: transparent;\n}",
"h2 {\n font-weight: 300;\n}",
"h3 {\n font-weight: 200;\n}"
]
Run Code Online (Sandbox Code Playgroud)
我还想指出RegExp并不是我的强项,我不太确定RegEx使用什么,但我认为我可以使用RegExp和它[].split(...);来实现这一点.
甚至可以使用RegExp来消除在分割代码块之前整理样式表的需要.
注意:我已经检查了这个问题,但不幸的是,这也没有帮助.
这个实现是使用tinycss一个简单的纯 python css 解析器完成的。
这适用于未整理的css。只要是合法的。
import tinycss
from collections import defaultdict
parser = tinycss.make_parser('page3')
# use parse_stylesheet_files to read from a file.
stylesheet = parser.parse_stylesheet("""h1 {color: #333; background-color: transparent}
h2 {
font-weight:300
}
h3
{
font-weight: 200
}
h1{
padding: 0px;}
""")
# Initialize to empty list if key does not exists
# This allows to group multiple blocks with same selectors
temp = defaultdict(list)
for rule in stylesheet.rules:
for dec in rule.declarations:
temp[rule.selector.as_css()].append((dec.name, dec.value.as_css()))
print(temp)
Run Code Online (Sandbox Code Playgroud)
输出:
defaultdict(<class 'list'>,
{'h1': [('color', '#333'),
('background-color', 'transparent'),
('padding', '0px')],
'h2': [('font-weight', '300')],
'h3': [('font-weight', '200')]})
Run Code Online (Sandbox Code Playgroud)
了解不同的h1块如何组合到一个列表中。我不太清楚 CSS 的复杂性,但是很容易防止这种情况发生。
与使用正则表达式的解决方案不同,它更加灵活,因为它涵盖了所有边缘情况,可与选择器、CSS2 和 CSS3 一起使用。
请注意:我已将所有内容放入字典中,但您也可以轻松地将其作为列表推送。如果您想要纯列表的东西,请告诉我,但如果您了解我在做什么,那么它应该相对微不足道。