Python字典键丢失
我想我应该编写一个快速脚本来整合我在多个CSS文件中发布的CSS规则,然后我可以缩小它 我是Python新手,但我认为这是一个尝试新语言的好练习。我的主循环没有像我想象的那样解析CSS 我用从CSS文件解析的选择器填充一个列表,以按顺序返回CSS规则。在脚本的后面,该列表包含字典中找不到的元素Python字典键丢失,python,parsing,dictionary,list,Python,Parsing,Dictionary,List,我想我应该编写一个快速脚本来整合我在多个CSS文件中发布的CSS规则,然后我可以缩小它 我是Python新手,但我认为这是一个尝试新语言的好练习。我的主循环没有像我想象的那样解析CSS 我用从CSS文件解析的选择器填充一个列表,以按顺序返回CSS规则。在脚本的后面,该列表包含字典中找不到的元素 for line in self.file.readlines(): if self.hasSelector(line): selector = self.getSel
for line in self.file.readlines():
if self.hasSelector(line):
selector = self.getSelector(line)
if selector not in self.order:
self.order.append(selector)
elif selector and self.hasProperty(line):
# rules.setdefault(selector,[]).append(self.getProperty(line))
property = self.getProperty(line)
properties = [] if selector not in rules else rules[selector]
if property not in properties:
properties.append(property)
rules[selector] = properties
# print "%s :: %s" % (selector, "".join(rules[selector]))
return rules
遇到错误:
$ css-combine combined.css test1.css test2.css
Traceback (most recent call last):
File "css-combine", line 108, in <module>
c.run(outfile, stylesheets)
File "css-combine", line 64, in run
[(selector, rules[selector]) for selector in parser.order],
KeyError: 'p'
文件2:
body {
font-size: 16px;
}
#header .title {
font-family: Tahoma, Geneva, sans-serif;
font-size: 1.9em;
}
#header .title a, #header .title a:hover {
color: #f5f5f5;
border-bottom: none;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 1);
}
提前感谢。更改
def hasProperty(self, line):
return True if re.search("^\s?[a-z-]+:[^;]+;", line) else False
到
hasProperty
不匹配任何内容,因为\s?
只匹配0或1个空白字符。对regexsr”“
使用原始字符串文字。您可以使用re.match
代替re.search(“^…
如果x为False,则返回True
可以替换为返回x
或返回bool(x)
+1谢谢,它通常是这么小的东西!这解释了为什么组合中缺少明显的随机属性。css
也是以多个空格作为前缀的行,而不是一个选项卡。
body {
background-color: #e7e7e7;
}
p {
margin: 1em 0em;
}
body {
font-size: 16px;
}
#header .title {
font-family: Tahoma, Geneva, sans-serif;
font-size: 1.9em;
}
#header .title a, #header .title a:hover {
color: #f5f5f5;
border-bottom: none;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 1);
}
def hasProperty(self, line):
return True if re.search("^\s?[a-z-]+:[^;]+;", line) else False
def hasProperty(self, line):
return True if re.search("^\s*[a-z-]+:[^;]+;", line) else False