当前位置: 首页>>代码示例>>Python>>正文


Python tinycss.make_parser函数代码示例

本文整理汇总了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
开发者ID:brad,项目名称:font-to-png,代码行数:25,代码来源:font-to-png.py

示例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
开发者ID:dewww,项目名称:HTMLEditor-Pythonista,代码行数:33,代码来源:themes.py

示例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"]
开发者ID:karlcow,项目名称:compatipede,代码行数:28,代码来源:browser.py

示例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
开发者ID:andrewhead,项目名称:tutorons-server,代码行数:34,代码来源:detect.py

示例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
开发者ID:nerdfiles,项目名称:css-sempai,代码行数:27,代码来源:sempai.py

示例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
开发者ID:jasonruyle,项目名称:compression,代码行数:25,代码来源:encode.py

示例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"]
开发者ID:seiflotfy,项目名称:compatipede,代码行数:29,代码来源:browser.py

示例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)
开发者ID:sergeospb,项目名称:liveweb,代码行数:35,代码来源:wayback.py

示例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
开发者ID:Cobaltians-Fonts,项目名称:fontToCobalt,代码行数:26,代码来源:css.py

示例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 = {}
开发者ID:sergey1kabanov,项目名称:tourist,代码行数:9,代码来源:smiles.py

示例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
开发者ID:jaywuuu,项目名称:css_checker,代码行数:9,代码来源:css_check.py

示例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
开发者ID:benastan,项目名称:css-audit,代码行数:9,代码来源:models.py

示例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)
开发者ID:tyerq,项目名称:load_testing,代码行数:10,代码来源:auction.py

示例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
开发者ID:jschaul,项目名称:talkshow,代码行数:10,代码来源:parseCSS.py

示例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
开发者ID:superisaac,项目名称:fa2icon,代码行数:11,代码来源:fa2icon.py


注:本文中的tinycss.make_parser函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。