diff options
| author | Michael Williamson <mike@zwobble.org> | 2016-03-14 08:10:01 +0000 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2016-03-14 20:09:13 +0000 |
| commit | 00cfd0d5bae2e7688754dfc458016d42abfcd037 (patch) | |
| tree | 24b49bdad94d9c34c755ec50e0db5fb39a34aee8 /mammoth/html/__init__.py | |
| parent | 2329dbcbbc945437256569c789b127e454069c98 (diff) | |
Add HTML AST with strip_empty function
Diffstat (limited to 'mammoth/html/__init__.py')
| -rw-r--r-- | mammoth/html/__init__.py | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/mammoth/html/__init__.py b/mammoth/html/__init__.py new file mode 100644 index 0000000..905b423 --- /dev/null +++ b/mammoth/html/__init__.py @@ -0,0 +1,58 @@ +from ..lists import flat_map +from .nodes import TextNode, Element, SelfClosingElement, ForceWrite, NodeVisitor + + +def text(value): + return TextNode(value) + + +def element(tag_name, attributes=None, children=None): + if attributes is None: + attributes = {} + if children is None: + children = [] + + return Element([tag_name], attributes, children, collapsible=False) + + +def self_closing_element(tag_name, attributes=None): + if attributes is None: + attributes = {} + + return SelfClosingElement(tag_name, attributes) + + +force_write = ForceWrite() + + +def strip_empty(nodes): + return flat_map(_strip_empty_node, nodes) + + +def _strip_empty_node(node): + return StripEmpty().visit(node) + + +class StripEmpty(NodeVisitor): + def visit_text_node(self, node): + if node.value: + return [node] + else: + return [] + + def visit_element(self, element): + children = strip_empty(element.children) + if len(children) == 0: + return [] + else: + return [Element( + element.tag_names, + element.attributes, + children, + collapsible=element.collapsible)] + + def visit_self_closing_element(self, element): + return [element] + + def visit_force_write(self, node): + return [node] |
