本文整理汇总了Python中tinycss.make_parser函数的典型用法代码示例。如果您正苦于以下问题:Python make_parser函数的具体用法?Python make_parser怎么用?Python make_parser使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_parser函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, filename, font_class_prefix):
import tinycss
global icons
new_icons = {}
parser = tinycss.make_parser("page3")
stylesheet = parser.parse_stylesheet_file(filename)
is_icon = re.compile(u("\.%s(.*):before,?" % font_class_prefix))
for rule in stylesheet.rules:
selector = rule.selector.as_css()
for match in is_icon.finditer(selector):
name = match.groups()[0]
for declaration in rule.declarations:
if declaration.name == u"content":
val = declaration.value.as_css()
if val.startswith('"') and val.endswith('"'):
val = val[1:-1]
try:
new_icons[name] = uchr(int(val[1:], 16))
except UnicodeEncodeError:
new_icons[name] = val[1:]
except ValueError:
new_icons[name] = u(val[1:])
except:
pass
icons = new_icons
示例2: get_background_color
def get_background_color():
themes = {"default": ("#000000", "#FFFFFF")}
p = theme_path()
themes_list = list_themes()
par = tinycss.make_parser("page3")
for file in themes_list:
with open("%s/%s" % (p, file), "r") as f:
style = par.parse_stylesheet_file(f)
i = [str(x) for x in style.rules]
index = 0
for x in i:
if x.endswith("CodeMirror>"):
break
else:
index += 1
if index < len(style.rules):
decs = style.rules[index].declarations
background = ""
text = ""
for dec in decs:
if dec.name == "background":
background = str(dec.value.as_css())
if dec.name == "color":
text = str(dec.value.as_css())
if background == "":
background = "#FFFFFF"
if text == "":
text = "#000000"
themes[file.replace(".css", "")] = (background, text)
background = ""
text = ""
return themes
示例3: _find_css_problems
def _find_css_problems(self, sheets):
issues = []
try:
parser = tinycss.make_parser()
for key, value in sheets.iteritems():
parsed_sheet = parser.parse_stylesheet_bytes(value.encode('utf8'))
for rule in parsed_sheet.rules:
look_for_decl = []
# process_rule will go through rule.declarations and fill look_for_decl with a list of potential problems
self._process_rule(rule, look_for_decl)
# having gone through all declarations in the rule, we now have a list of
# "equivalent" rule names or name:value sets - so we go through the declarations
# again - and check if the "equivalents" are present
look_for_decl[:] = [x for x in look_for_decl if not self._found_in_rule(rule, x)] # replace list by return of list comprehension
# the idea is that if all "problems" had equivalents present,
# the look_for_decl list will now be empty
for issue in look_for_decl:
dec = issue["dec"];
issues.append(dec.name +
' used without equivalents for '+issue["sel"]+' in ' +
key + ':' + str(dec.line) +
':' + str(dec.column) +
', value: ' +
dec.value.as_css())
except Exception, e:
print e
return ["ERROR PARSING CSS"]
示例4: extract
def extract(self, node):
textfield = ''.join(map(filter_non_ascii, node.text))
textfield_as_list = textfield.split('\n')
ss_offset = 0
# sets textfield to the text in the style tag, if exists and adjusts the offset
if BeautifulSoup(textfield).style:
ss_offset = textfield.find("<style>") + len("<style>")
textfield = ''.join(map(filter_non_ascii, BeautifulSoup(textfield).style.text))
textfield_as_list = textfield.split('\n')
# parses textfield as a stylesheet
parser = tinycss.make_parser()
stylesheet = parser.parse_stylesheet(textfield)
valid_regions = []
# calculate the start index of the selector
for rule in stylesheet.rules:
sel = rule.selector
ss_start = ss_offset
if sel.line > 1:
for l in xrange(sel.line - 1):
# add 1 to account for newline characters
ss_start += len(textfield_as_list[l]) + 1
ss_start += sel.column - 1
sel = rule.selector.as_css()
if rule.declarations:
valid_regions.append(Region(node, ss_start, ss_start + len(sel) - 1, sel))
# check if the regions found contain valid selectors
for region in valid_regions:
if not is_selector(region.string):
valid_regions.remove(region)
return valid_regions
示例5: load_module
def load_module(self, name):
if name in sys.modules:
return sys.modules[name]
mod = imp.new_module(name)
mod.__file__ = self.css_path
mod.__loader__ = self
#decoder = json.JSONDecoder(object_hook=DottedDict)
parser = tinycss.make_parser('page3')
try:
stylesheet = parser.parse_stylesheet_file(self.css_path)
except:
raise ImportError(
'Could not open file.')
b = {}
#import pdb; pdb.set_trace()
for i in stylesheet.rules:
b[i.selector.as_css()] = i.declarations
mod.__dict__.update(b)
sys.modules[name] = mod
return mod
示例6: genUsedNamesDictionary
def genUsedNamesDictionary(data):
propCountDictionary={}
parser = tinycss.make_parser('page3')
stylesheet = parser.parse_stylesheet_bytes(data)
for rle in stylesheet.rules:
if not hasattr(rle, 'declarations'): continue
for prop in rle.declarations:
#print prop.name
if prop.name in propCountDictionary:
propCountDictionary[prop.name] += 1
else:
propCountDictionary[prop.name] = 1
valsDict = sorted(propCountDictionary.iteritems(), key=operator.itemgetter(1), reverse=True)
sortedVals = []
for k,v in valsDict:
#print k
sortedVals.append(k)
return sortedVals
示例7: _find_css_problems
def _find_css_problems(self, sheets):
issues_json = []
try:
parser = tinycss.make_parser()
for key, value in sheets.iteritems():
parsed_sheet = parser.parse_stylesheet_bytes(value.encode('utf8'))
for rule in parsed_sheet.rules:
look_for_decl = []
# process_rule will go through rule.declarations and fill look_for_decl with a list of potential problems
self._process_rule(rule, look_for_decl)
# having gone through all declarations in the rule, we now have a list of
# "equivalent" rule names or name:value sets - so we go through the declarations
# again - and check if the "equivalents" are present
look_for_decl[:] = [x for x in look_for_decl if not self._found_in_rule(rule, x)] # replace list by return of list comprehension
# the idea is that if all "problems" had equivalents present,
# the look_for_decl list will now be empty
for issue in look_for_decl:
dec = issue["dec"];
name = dec.name
if '-webkit-' in name:
name = name[8:]
if name in LOG_CSS_PROPS or re.search(LOG_CSS_VALUES, dec.value.as_css()):
issues_json.append({"file": key, "selector": issue["sel"], "property":dec.name, "value":dec.value.as_css()})
else:
print('ignored %s ' % dec.name)
except Exception, e:
print e
return ["ERROR PARSING CSS"]
示例8: rewrite_css
def rewrite_css(self, base_url, css, append_line=None):
_css_base_url = base_url.replace(os.path.basename(base_url), '')
parser = tinycss.make_parser()
css_columns = css.split("\n")
count_replaced = 0
for rule in parser.parse_stylesheet(css).rules:
if hasattr(rule, 'uri') and hasattr(rule, 'at_keyword'):
if rule.at_keyword == "@import":
logging.debug("Found import rule in css %s" % rule.uri)
if not rule.uri.startswith('http://') or rule.uri.startswith('https://'):
url2 = _css_base_url + rule.uri
else:
url2 = tok.value
if append_line:
url2 = append_line + url2
css_columns[rule.line - 1] = css_columns[rule.line - 1].replace(rule.uri, url2)
logging.debug("rewrote %r => %r at line %s" % (rule.uri, url2, rule.line))
count_replaced += 1
elif hasattr(rule, 'declarations'):
for declaration in rule.declarations:
for tok in declaration.value:
if tok.type == 'URI' and not tok.value.startswith("data:image"):
logging.debug("Found uri rule in css %s" % tok.value)
if not tok.value.startswith('http://') or tok.value.startswith('https://'):
url2 = urlparse.urljoin(base_url, tok.value)
else:
url2 = tok.value
if append_line:
url2 = append_line + url2
css_columns[tok.line - 1] = css_columns[tok.line - 1].replace(tok.value, url2)
logging.debug("rewrote %r => %r at line %s" % (tok.value, url2, rule.line))
count_replaced += 1
logging.debug("%s css rules replaced in %s" % (count_replaced, base_url))
return '\n'.join(css_columns)
示例9: parseCSS
def parseCSS(file):
parser = tinycss.make_parser('page3')
stylesheet = parser.parse_stylesheet_file(file);
global prefix
global fontName
first = True
content = False
for rule in stylesheet.rules:
# get raw glyph and name
glyph = rule.declarations
name = rule.selector.as_css().split(':', 1)[0].replace('.', '')
if first == True:
fontName = glyph[0].value.as_css().replace('\'', '').replace('"', '') # set fontName
first = False
else:
if prefix == '': # we dont have the prefix yet
tmp = rule.selector.as_css().split('-', 1)[0].replace('.', '')
if tmp[0] != '[' and tmp != '':
prefix = tmp # set the prefix we are looking for
if (glyph[0].value.as_css()[1] == '\\'):
content = True # font selector with needed content appeared
if content == True:
glyph = glyph[0].value.as_css().replace('"', '')
glyphs.append(glyph.lower()) # set a glyph in glyphs
if name[0] != '[':
names.append(name.lower()) # set a name in names
示例10: __init__
def __init__(self, settings):
conn = httplib.HTTPConnection('goodgame.ru')
conn.request('GET', '/css/compiled/chat.css')
response = conn.getresponse()
parser = tinycss.make_parser('page3')
self.css = parser.parse_stylesheet(response.read())
self.smiles = {}
self.imgs = {}
示例11: process_css_file
def process_css_file(file_path):
parser = tinycss.make_parser('page3')
stylesheet = parser.parse_stylesheet_file(file_path)
css_blocks = []
for rule in stylesheet.rules:
css_block = CSSBlock(rule.selector, rule.declarations)
css_blocks.append(css_block)
return css_blocks
示例12: get_parsed_sheet
def get_parsed_sheet(self):
source = self.get_latest_source()
if not hasattr(self, 'sheet'):
if self.inline is True:
source = self.extract_inline_source()
parser = tinycss.make_parser()
sheet = parser.parse_stylesheet(source)
self.sheet = sheet
return self.sheet
示例13: css
def css(self):
pq = PyQuery(self.tender_src)
for style in pq('link[rel="stylesheet"]'):
href = style.get('href')
if href and href.startswith('/'):
resp = self.client.get(href)
if resp.status_code == 200:
css = resp.content
self.csses.extend(tinycss.make_parser(CSSFontfaceParser).parse_stylesheet(unicode(css)).rules)
示例14: parseFile
def parseFile(self):
parser = tinycss.make_parser()
stylesheet = parser.parse_stylesheet_file(self.filename)
self.basicDict = {rule.selector.as_css():{declaration.name:declaration.value.as_css() for declaration in rule.declarations } for rule in stylesheet.rules}
try:
self.dict = {removeHashesAndDots(rule.selector.as_css()):{declaration.name:makeFloatsOutOfPercentages(declaration.value.as_css()) for declaration in rule.declarations } for rule in stylesheet.rules}
except Exception, e:
warn( "problem with submethod, only generating basicDict")
raise e
示例15: parse_css
def parse_css():
parser = tinycss.make_parser('page3')
stylesheet = parser.parse_stylesheet_file(CSS_FILENAME)
for rule in stylesheet.rules:
if isinstance(rule, tinycss.css21.RuleSet):
names = re.findall(r'\.(fa\-[\w\-]+):before\b', rule.selector.as_css())
for decl in rule.declarations:
if decl.name == 'content':
content_ord = int(decl.value.as_css()[2:-1], 16)
for iconname in names:
yield iconname, content_ord