• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python tinycss.make_parser函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tinycss.make_parser函数的典型用法代码示例。如果您正苦于以下问题:Python make_parser函数的具体用法?Python make_parser怎么用?Python make_parser使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了make_parser函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: _parseTechFile

	def _parseTechFile(self, fileName):
		"""
		Reads in a css techfile and builds necessary device map & default styles.

		Parameters
		----------
		fileName : string
			location of techfile

		Returns
		-------
		out : [defaultAttribs, deviceMap]
			List of two dictionaries. First describing default attributes,
			second linking tag names to the function meant to build them.
		"""

		cssparser = tinycss.make_parser()
		stylesheet = cssparser.parse_stylesheet_file(fileName)

		## Never modifying globals, just using to link text names to objects
		globs = globals()

		deviceMap = {}
		defaultAttribs = {}

		for rule in stylesheet.rules:
			# skip at rules
			if rule.at_keyword != None:
				continue



			# Grab the tag and declarations
			thisTag  = rule.selector[0]
			thisDecl = self._declaration2dict(rule.declarations)

			# In the declarations, we require a 'libname' and 'devname'
			try:
				thisLib = thisDecl['libname']
				thisDev = thisDecl['devname']
			except:
				raise Exception( "FATAL: techfile is malformed at line "
								 + str(rule.line) )

			# Use these properties to map the tag to a builder function
			deviceMap[thisTag.value] = getattr(getattr(self,thisLib),thisDev)
			thisDecl.pop('libname')
			thisDecl.pop('devname')


			# Deal with the other declarations
			defaultAttribs[thisTag.value] = thisDecl

		return [defaultAttribs, deviceMap]
开发者ID:johnlb,项目名称:strange,代码行数:54,代码来源:__init__.py


示例17: find_stylesheets

def find_stylesheets(tree):
    """Find the stylesheets included in ``tree``."""
    # TODO: support contentStyleType on <svg>
    default_type = "text/css"
    for element in tree.iter():
        # http://www.w3.org/TR/SVG/styling.html#StyleElement
        if (element.tag == "style" and
                element.get("type", default_type) == "text/css"):
            # TODO: pass href for relative URLs
            # TODO: support media types
            # TODO: what if <style> has children elements?
            yield tinycss.make_parser().parse_stylesheet(element.text)
开发者ID:Borisenkov,项目名称:Printrun,代码行数:12,代码来源:css.py


示例18: find_stylesheets_rules

def find_stylesheets_rules(tree, stylesheet, url):
    """Find the rules in a stylesheet."""
    for rule in stylesheet.rules:
        if isinstance(rule, tinycss.css21.ImportRule):
            css_url = parse_url(rule.uri, url)
            stylesheet = tinycss.make_parser().parse_stylesheet(
                tree.fetch_url(css_url, 'text/css').decode('utf-8'))
            for rule in find_stylesheets_rules(tree, stylesheet,
                                               css_url.geturl()):
                yield rule
        if not rule.at_keyword:
            yield rule
开发者ID:ErikOnBike,项目名称:CairoSVG,代码行数:12,代码来源:css.py


示例19: test_make_parser

def test_make_parser():
    class MyParser(object):
        def __init__(self, some_config):
            self.some_config = some_config

    parsers = [
        make_parser(),
        make_parser('page3'),
        make_parser(CSSPage3Parser),
        make_parser(MyParser, some_config=42),
        make_parser(CSSPage3Parser, MyParser, some_config=42),
        make_parser(MyParser, 'page3', some_config=42),
    ]

    for parser, exp in zip(parsers, [False, True, True, False, True, True]):
        assert isinstance(parser, CSSPage3Parser) == exp

    for parser, exp in zip(parsers, [False, False, False, True, True, True]):
        assert isinstance(parser, MyParser) == exp

    for parser in parsers[3:]:
        assert parser.some_config == 42

    # Extra or missing named parameters
    raises(TypeError, make_parser, some_config=4)
    raises(TypeError, make_parser, 'page3', some_config=4)
    raises(TypeError, make_parser, MyParser)
    raises(TypeError, make_parser, MyParser, some_config=4, other_config=7)
开发者ID:SimonSapin,项目名称:tinycss,代码行数:28,代码来源:test_api.py


示例20: _get_styles

 def _get_styles(self):
     """Gets all CSS content from and removes all <link rel="stylesheet"> and
     <style> tags concatenating into one CSS string which is then parsed with
     cssutils and the resulting CSSStyleSheet object set to
     `self.stylesheet`.
     """
     self._get_external_styles()
     self._get_internal_styles()
     for style_string in self.extra_style_strings:
         self.style_string += style_string
     import tinycss
     cssparser = tinycss.make_parser()
     self.stylesheet = cssparser.parse_stylesheet(self.style_string)
开发者ID:subblime,项目名称:pynliner,代码行数:13,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tinydb.where函数代码示例发布时间:2022-05-27
下一篇:
Python ip_connection.IPConnection类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap