Example #1
0
def swap_tree_given_left(left_tree: nltk.Tree,
                         displacement: List[int],
                         new_words=List[str]):
    """Swap left node with right node within a parent node."""
    nodes = [left_tree]
    right_tree = left_tree.right_sibling()
    parent_tree = left_tree.parent()
    # Get all tree pointer
    for disp in displacement:
        # disp = -1 indicates that is a new word, skip
        if disp == -1:
            continue
        nodes.append(right_tree)

        right_tree = right_tree.right_sibling()
        if right_tree == None:
            break

    # Remove all siblings and left-most self
    for node in nodes:
        parent_tree.remove(node)

    # Append with new displacement
    for disp in displacement:
        # disp = -1 indicates that is a new word
        if disp == -1:
            new_word = PTree('NEW', [new_words.pop(0)])
            parent_tree.append(new_word)
        else:
            parent_tree.append(nodes[disp])

    return parent_tree
Example #2
0
def build_grammar_str_from_left_most(tree: nltk.Tree):

    left_pt = tree.left_sibling()
    right_pt = tree.right_sibling()
    parent_pt = tree.parent()

    grammar_str = None

    if parent_pt != None:
        grammar_str = f"{parent_pt.label()} -> {tree.label()}"

        # Build grammar from leftmost node in the subtree
        if left_pt == None and right_pt != None:
            while right_pt != None:
                grammar_str += f" {right_pt.label()}"
                right_pt = right_pt.right_sibling()
    return grammar_str
Example #3
0
def swap_tree_given_left(left_tree: nltk.Tree, displacement: list):
    """
    swap left node with right node within a parent node 
    """

    nodes = [left_tree]
    right_tree = left_tree.right_sibling()
    parent_tree = left_tree.parent()

    # Get all tree pointer
    for i in range(len(displacement) - 1):
        nodes.append(right_tree)

    # Remove all siblings and left-most self
    for node in nodes:
        parent_tree.remove(node)

    # Append with new displacement
    for disp in displacement:
        parent_tree.append(nodes[disp])

    return parent_tree