Python lxml.etree 模块,Comment() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用lxml.etree.Comment()。
def _apply_rule(self, rule: Rule) -> None:
traverser = self._get_traverser(rule.traversal_order)
dbg('Using traverser: {}'.format(traverser))
for element in traverser(self.states.root):
if element.tag is etree.Comment or element.tag is etree.Entity:
continue
dbg('Evaluating {}.'.format(element))
self.states.current_element = element
try:
if self._test_conditions(element, rule.conditions):
self._apply_handlers(*rule.handlers)
except AbortRule:
dbg('Aborting rule.')
break
except SkipToNextElement:
dbg('Skipping to next element.')
continue
self.states.current_element = None
def get_stellar_components(self, include_comments=False):
# Get the stellar system
stellar_system = self.get_stellar_system()
# Get the 'components' element
stellar_components_parents = stellar_system.xpath("components")
# Check if only one 'components' element is present
if len(stellar_components_parents) == 0: raise ValueError("Stellar system is not composed of components")
elif len(stellar_components_parents) > 1: raise ValueError("Invalid ski file: multiple 'components' objects within stellar system")
stellar_components = stellar_components_parents[0]
# Return the stellar components as a list
if include_comments: return stellar_components.getchildren()
else: return [component for component in stellar_components.getchildren() if component.tag is not etree.Comment]
## This function returns the list of stellar component names
def get_dust_components(self, include_comments=False):
# Get the dust distribution
dust_distribution = self.get_dust_distribution()
# Check whether the dust distribution is a CompDustdistribution
if not dust_distribution.tag == "CompDustdistribution": raise ValueError("Dust distribution is not composed of components")
# Get the 'components' element
dust_components_parents = dust_distribution.xpath("components")
# Check if only one 'components' element is present
if len(dust_components_parents) == 0: raise ValueError("Dust distribution is not composed of components")
elif len(dust_components_parents) > 1: raise ValueError("Invalid ski file: multiple 'components' objects within dust distribution")
dust_components = dust_components_parents[0]
# Return the dust components as a list
if include_comments: return dust_components.getchildren()
else: return [component for component in dust_components.getchildren() if component.tag is not etree.Comment]
## This functions returns a list with the ids of the different dust components (the id is a name if this is defined
# for the component,otherwise it is the index of the component)
def remove_stellar_component(self, component_id):
# Get the stellar component with the specified ID
component = self.get_stellar_component(component_id)
# Get the prevIoUs item
prevIoUs = component.getprevIoUs()
# Get the parent
parent = component.getparent()
# Check whether the prevIoUs item is a comment
if prevIoUs.tag is etree.Comment:
# If the comment states the component ID,remove it
if prevIoUs.text.strip() == component_id: parent.remove(prevIoUs)
# If the comment preceeding the component does not have the name of that component (it must by deFinition),
# something strange is going on ...
else: raise ValueError("Something is wrong with the ski file")
# Remove the stellar component
parent.remove(component)
## This function removes the dust component with the specified ID
def remove_dust_component(self, component_id):
# Get the dust component with the specified ID
component = self.get_dust_component(component_id)
# Get the prevIoUs item
prevIoUs = component.getprevIoUs()
# Get the parent
parent = component.getparent()
# Check whether the prevIoUs item is a comment
if prevIoUs.tag is etree.Comment:
# If the comment states the component ID,
# something strange is going on ...
else: raise ValueError("Something is wrong with the ski file")
# Remove the dust component
parent.remove(component)
## This function removes the stellar components except for the component(s) with the specified ID(s)
def get_stellar_components(self, include_comments=False):
# Get the stellar system
stellar_system = self.get_stellar_system()
# Get the 'components' element
stellar_components_parents = stellar_system.xpath("components")
# Check if only one 'components' element is present
if len(stellar_components_parents) == 0: raise ValueError("Stellar system is not composed of components")
elif len(stellar_components_parents) > 1: raise ValueError("Invalid ski file: multiple 'components' objects within stellar system")
stellar_components = stellar_components_parents[0]
# Return the stellar components as a list
if include_comments: return stellar_components.getchildren()
else: return [component for component in stellar_components.getchildren() if component.tag is not etree.Comment]
## This function returns the list of stellar component names
def get_dust_components(self,otherwise it is the index of the component)
def remove_stellar_component(self,
# something strange is going on ...
else: raise ValueError("Something is wrong with the ski file")
# Remove the stellar component
parent.remove(component)
## This function removes the dust component with the specified ID
def remove_dust_component(self,
# something strange is going on ...
else: raise ValueError("Something is wrong with the ski file")
# Remove the dust component
parent.remove(component)
## This function removes the stellar components except for the component(s) with the specified ID(s)
def make_path(self, node, elements):
if elements:
elem = elements[0]
children = node.xpath(elem, namespaces=self.NSMAP)
if not children:
name = elements[0]
for ns, url in six.iteritems(self.NSMAP):
ns_token = ns + ':'
url_token = '{' + url + '}'
name = name.replace(ns_token, url_token)
child = etree.Element(name)
node.insert(0, child)
node.insert(0, etree.Comment(" section added by maintainer "))
self.reformat(node, node[:2])
else:
child = children[0]
return self.make_path(child, elements[1:])
return node
def getNodeDetails(self, node):
if isinstance(node, tuple): # Text node
node, key = node
assert key in ("text", "tail"), "Text nodes are text or tail,found %s" % key
return base.TEXT, ensure_str(getattr(node, key))
elif isinstance(node, Root):
return (base.DOCUMENT,)
elif isinstance(node, Doctype):
return base.DOCTYPE, node.name, node.public_id, node.system_id
elif isinstance(node, FragmentWrapper) and not hasattr(node, "tag"):
return base.TEXT, ensure_str(node.obj)
elif node.tag == etree.Comment:
return base.COMMENT, ensure_str(node.text)
elif node.tag == etree.Entity:
return base.ENTITY, ensure_str(node.text)[1:-1] # strip &;
else:
# This is assumed to be an ordinary element
match = tag_regexp.match(ensure_str(node.tag))
if match:
namespace, tag = match.groups()
else:
namespace = None
tag = ensure_str(node.tag)
attrs = {}
for name, value in list(node.attrib.items()):
name = ensure_str(name)
value = ensure_str(value)
match = tag_regexp.match(name)
if match:
attrs[(match.group(1), match.group(2))] = value
else:
attrs[(None, name)] = value
return (base.ELEMENT, namespace, self.filter.fromXmlName(tag),
attrs, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, _("Text nodes are text or tail,found %s") % key
return _base.TEXT, Root):
return (_base.DOCUMENT, Doctype):
return _base.DOCTYPE, FragmentWrapper) and node.isstring:
return _base.TEXT, node.obj
elif node.tag == etree.Comment:
return _base.COMMENT, ensure_str(node.text)
elif node.tag == etree.Entity:
return _base.ENTITY, name)] = value
return (_base.ELEMENT, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, tuple): # Text node
node, getattr(node, key)
elif isinstance(node, node
elif node.tag == etree.Comment:
return _base.COMMENT, node.text
elif node.tag == etree.Entity:
return _base.ENTITY, node.text[1:-1] # strip &;
else:
#This is assumed to be an ordinary element
match = tag_regexp.match(node.tag)
if match:
namespace, tag = match.groups()
else:
namespace = None
tag = node.tag
attrs = {}
for name, value in node.attrib.items():
match = tag_regexp.match(name)
if match:
attrs[(match.group(1),match.group(2))] = value
else:
attrs[(None,name)] = value
return (_base.ELEMENT,
attrs, len(node) > 0 or node.text)
def getNodeDetails(self,found %s" % key
return _base.TEXT, "tag"):
return _base.TEXT, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
def _parse_element_r(self, el, specials, refs, id=None, element_cls=Paragraph):
"""Recursively parse HTML/XML element and its children into a list of Document elements."""
elements = []
if el.tag in {etree.Comment, etree.ProcessingInstruction}:
return []
# if el in refs:
# return [element_cls('',references=refs[el])]
if el in specials:
return specials[el]
id = el.get('id', id)
references = refs.get(el, [])
if el.text is not None:
elements.append(element_cls(six.text_type(el.text), id=id, references=references))
elif references:
elements.append(element_cls('', references=references))
for child in el:
# br is a special case - technically inline,but we want to split
if child.tag not in {etree.Comment, etree.ProcessingInstruction} and child.tag.lower() == 'br':
elements.append(element_cls(''))
child_elements = self._parse_element_r(child, specials=specials, refs=refs, element_cls=element_cls)
if (self._is_inline(child) and len(elements) > 0 and len(child_elements) > 0 and
isinstance(elements[-1], (Text, Sentence)) and isinstance(child_elements[0], Sentence)) and
type(elements[-1]) == type(child_elements[0])):
elements[-1] += child_elements.pop(0)
elements.extend(child_elements)
if child.tail is not None:
if self._is_inline(child) and len(elements) > 0 and isinstance(elements[-1], element_cls):
elements[-1] += element_cls(six.text_type(child.tail), id=id)
else:
elements.append(element_cls(six.text_type(child.tail), id=id))
return elements
def _is_inline(self, element):
"""Return True if an element is inline."""
if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements:
return True
return False
def component_from_library(parent, paths, lib, name, value, ref, pos, placeholder=True, remapping={}):
if not name:
return
f = get_model_file(paths, remapping)
if not f:
print("Warning: component '{}' from library '{}' was not found".format(name, lib))
if placeholder:
etree.SubElement(parent, "rect", x=str(ki2dmil(pos[0])), y=str(ki2dmil(pos[1])),
width="300", height="300", style="fill:red;")
return
parent.append(etree.Comment("{}:{}".format(lib, name)))
r = etree.SubElement(parent, "g")
for x in extract_svg_content(f):
r.append(x)
origin_x = 0
origin_y = 0
origin = r.find(".//*[@id='origin']")
if origin is not None:
origin_x = float(origin.attrib["x"])
origin_y = float(origin.attrib["y"])
origin.getparent().remove(origin)
else:
print("Warning: component '{}' from library '{}' has no ORIGIN".format(name, lib))
r.attrib["transform"] = "translate({} {}) scale(393.700787402) rotate({}) translate({},{})".format(
ki2dmil(pos[0]), ki2dmil(pos[1]),
-math.degrees(pos[2]), -origin_x, -origin_y)
def insertRoot(self, name):
buf = []
if self.doctype and self.doctype.name:
buf.append('<!DOCTYPE %s' % self.doctype.name)
if self.doctype.publicId is not None or self.doctype.systemId is not None:
buf.append(' PUBLIC "%s" "%s"' % (self.doctype.publicId,
self.doctype.systemId))
buf.append('>')
buf.append('<html></html>')
root = html.fromstring(''.join(buf))
# Append the initial comments:
for comment in self.initialComments:
root.addprevIoUs(etree.Comment(comment))
# Create the root document and add the ElementTree to it
self.document = self.documentClass()
self.document._elementTree = root.getroottree()
# Add the root element to the internal child/open data structures
root_element = self.elementClass(name)
root_element._element = root
self.document.childNodes.append(root_element)
self.openElements.append(root_element)
self.rootInserted = True
def insertRoot(self,
self.doctype.systemId))
buf.append('>')
buf.append('<html></html>')
root = html.fromstring(''.join(buf))
# Append the initial comments:
for comment in self.initialComments:
root.addprevIoUs(etree.Comment(comment))
# Create the root document and add the ElementTree to it
self.document = self.documentClass()
self.document._elementTree = root.getroottree()
# Add the root element to the internal child/open data structures
root_element = self.elementClass(name)
root_element._element = root
self.document.childNodes.append(root_element)
self.openElements.append(root_element)
self.rootInserted = True
def kill_conditional_comments(self, doc):
"""
IE conditional comments basically embed HTML that the parser
doesn't normally see. We can't allow anything like that,so
we'll kill any comments that Could be conditional.
"""
bad = []
self._kill_elements(
doc, lambda el: _conditional_comment_re.search(el.text),
etree.Comment)
def getNodeDetails(self, len(node) > 0 or node.text)
def getNodeDetails(self, len(node) > 0 or node.text)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。