我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用genshi.core.Attrs()。
def _interpolate_attrs(self, stream): for kind, data, pos in stream: if kind is START: # Record any directive attributes in start tags tag, attrs = data new_attrs = [] for name, value in attrs: if value: value = list(interpolate(value, self.filepath, pos[1], pos[2], lookup=self.lookup)) if len(value) == 1 and value[0][0] is TEXT: value = value[0][1] new_attrs.append((name, value)) data = tag, Attrs(new_attrs) yield kind, data, pos
def select(self, path): """Mark events matching the given XPath expression, within the current selection. >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer().select('.//em').trace()) (None, ('START', (QName('body'), Attrs()), (None, 1, 0))) (None, ('TEXT', u'Some ', (None, 1, 6))) ('ENTER', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('INSIDE', ('TEXT', u'test', (None, 1, 15))) ('EXIT', ('END', QName('em'), (None, 1, 19))) (None, ('TEXT', u' text', (None, 1, 24))) (None, ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :param path: an XPath expression (as string) or a `Path` instance :return: the stream augmented by transformation marks :rtype: `Transformer` """ return self.apply(SelectTransformation(path))
def end(self): """End current selection, allowing all events to be selected. Example: >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer('//em').end().trace()) ('OUTSIDE', ('START', (QName('body'), Attrs()), (None, 1, 0))) ('OUTSIDE', ('TEXT', u'Some ', (None, 1, 6))) ('OUTSIDE', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('OUTSIDE', ('TEXT', u'test', (None, 1, 15))) ('OUTSIDE', ('END', QName('em'), (None, 1, 19))) ('OUTSIDE', ('TEXT', u' text', (None, 1, 24))) ('OUTSIDE', ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :return: the stream augmented by transformation marks :rtype: `Transformer` """ return self.apply(EndTransformation()) #{ Deletion operations
def trace(self, prefix='', fileobj=None): """Print events as they pass through the transform. >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer('em').trace()) (None, ('START', (QName('body'), Attrs()), (None, 1, 0))) (None, ('TEXT', u'Some ', (None, 1, 6))) ('ENTER', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('INSIDE', ('TEXT', u'test', (None, 1, 15))) ('EXIT', ('END', QName('em'), (None, 1, 19))) (None, ('TEXT', u' text', (None, 1, 24))) (None, ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :param prefix: a string to prefix each event with in the output :param fileobj: the writable file-like object to write to; defaults to the standard output stream :rtype: `Transformer` """ return self.apply(TraceTransformation(prefix, fileobj=fileobj)) # Internal methods
def ET(element): """Convert a given ElementTree element to a markup stream. :param element: an ElementTree element :return: a markup stream """ tag_name = QName(element.tag.lstrip('{')) attrs = Attrs([(QName(attr.lstrip('{')), value) for attr, value in element.items()]) yield START, (tag_name, attrs), (None, -1, -1) if element.text: yield TEXT, element.text, (None, -1, -1) for child in element.getchildren(): for item in ET(child): yield item yield END, tag_name, (None, -1, -1) if element.tail: yield TEXT, element.tail, (None, -1, -1)
def to_genshi(walker): text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
def as_scalar(value): """Convert value to a scalar. If a single element Attrs() object is passed the value of the single attribute will be returned.""" if isinstance(value, Attrs): assert len(value) == 1 return value[0][1] else: return value
def __call__(self, kind, data, pos, namespaces, variables): namespace = Namespace(namespaces.get(self.prefix)) if kind is START: if self.principal_type is ATTRIBUTE and data[1]: return Attrs([(name, value) for name, value in data[1] if name in namespace]) or None else: return data[0] in namespace
def __call__(self, kind, data, pos, namespaces, variables): if kind is START: if self.principal_type is ATTRIBUTE and self.name in data[1]: return Attrs([(self.name, data[1].get(self.name))]) else: return data[0].localname == self.name
def __call__(self, kind, data, pos, namespaces, variables): qname = QName('%s}%s' % (namespaces.get(self.prefix), self.name)) if kind is START: if self.principal_type is ATTRIBUTE and qname in data[1]: return Attrs([(self.name, data[1].get(self.name))]) else: return data[0] == qname
def test_translate_included_attribute_text(self): """ Verify that translated attributes end up in a proper `Attrs` instance. """ html = HTML(u"""<html> <span title="Foo"></span> </html>""") translator = Translator(lambda s: u"Voh") stream = list(html.filter(translator)) kind, data, pos = stream[2] assert isinstance(data[1], Attrs)
def test_map_element(self): self.assertEqual( self._map('foo'), [(QName('foo'), Attrs([(QName('name'), u'foo'), (QName('size'), u'100')])), u'FOO', QName('foo')] )
def attr(self, name, value): """Add, replace or delete an attribute on selected elements. If `value` evaulates to `None` the attribute will be deleted from the element: >>> html = HTML('<html><head><title>Some Title</title></head>' ... '<body>Some <em class="before">body</em> <em>text</em>.</body>' ... '</html>', encoding='utf-8') >>> print(html | Transformer('body/em').attr('class', None)) <html><head><title>Some Title</title></head><body>Some <em>body</em> <em>text</em>.</body></html> Otherwise the attribute will be set to `value`: >>> print(html | Transformer('body/em').attr('class', 'emphasis')) <html><head><title>Some Title</title></head><body>Some <em class="emphasis">body</em> <em class="emphasis">text</em>.</body></html> If `value` is a callable it will be called with the attribute name and the `START` event for the matching element. Its return value will then be used to set the attribute: >>> def print_attr(name, event): ... attrs = event[1][1] ... print(attrs) ... return attrs.get(name) >>> print(html | Transformer('body/em').attr('class', print_attr)) Attrs([(QName('class'), u'before')]) Attrs() <html><head><title>Some Title</title></head><body>Some <em class="before">body</em> <em>text</em>.</body></html> :param name: the name of the attribute :param value: the value that should be set for the attribute. :rtype: `Transformer` """ return self.apply(AttrTransformation(name, value)) #{ Buffer operations
def _handle_start(self, tag, attrib): attrs = Attrs([(QName(name), value) for name, value in zip(*[iter(attrib)] * 2)]) self._enqueue(START, (QName(tag), attrs))
def handle_starttag(self, tag, attrib): fixed_attrib = [] for name, value in attrib: # Fixup minimized attributes if value is None: value = name fixed_attrib.append((QName(name), stripentities(value))) self._enqueue(START, (QName(tag), Attrs(fixed_attrib))) if tag in self._EMPTY_ELEMS: self._enqueue(END, QName(tag)) else: self._open_tags.append(tag)