From 856f9968e15b4efffd9c2ac229263b659576a96e Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Thu, 12 Dec 2013 22:14:06 +0000 Subject: Read nested HTML element paths --- mammoth/style_reader.py | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) (limited to 'mammoth') diff --git a/mammoth/style_reader.py b/mammoth/style_reader.py index 0c27bd8..7a7474f 100644 --- a/mammoth/style_reader.py +++ b/mammoth/style_reader.py @@ -4,19 +4,53 @@ from . import html_paths def read_html_path(string): - root_node = _grammar.parse(string) - tag_names = [root_node.children[0].text] + path_node = _grammar.parse(string) + return _read_path_node(path_node) - for choice_node in root_node.children[1].children: - tag_names.append(choice_node.children[1].text) + + +def _read_path_node(path_node): + elements = [ + _read_element_node(child) + for child in _repeated_children_with_separator(path_node, has_whitespace=True) + ] + return html_paths.path(elements) + + +def _read_element_node(node): + return html_paths.element(_read_tag_names_node(node)) + + +def _read_tag_names_node(node): + return [ + child.text + for child in _repeated_children_with_separator(node, has_whitespace=False) + ] + + +def _repeated_children_with_separator(node, has_whitespace): + yield node.children[0] + + if has_whitespace: + sequence_node_index = 2 + else: + sequence_node_index = 1 - return html_paths.path([html_paths.element(tag_names)]) + sequence_node = node.children[sequence_node_index] + for child in sequence_node.children: + yield child.children[sequence_node_index] -_grammar = Grammar(""" +_grammar = Grammar(r""" + +path = element whitespace* (">" whitespace* element)* + +element = tag_names tag_names = identifier ("|" identifier)* identifier = ~"[A-Z0-9]*"i +whitespace = ~"\s"* + """) -- cgit v1.2.3