LINUX.ORG.RU

История изменений

Исправление rtxtxtrx, (текущая версия) :

Честно говоря, то срань какая-то. Я про ту утилиту.

#!/usr/bin/env python
from __future__ import annotations

from dataclasses import dataclass, field


@dataclass
class Node:
    children: list[Node] = field(default_factory=list)
    parent: Node | None = None

    def add_child(self, child: Node) -> None:
        child.parent = self
        self.children.append(child)


@dataclass
class TagNode(Node):
    tag: str = ""


@dataclass
class TextNode(Node):
    text: str = ""


def parse_expression(expression: str) -> Node:
    pos = 0
    root = TagNode(tag="root")
    cur = root

    while ~(pos := expression.find("<")):
        end_pos = expression.find(">", pos + 1)

        if txt := expression[:pos]:
            cur.add_child(TextNode(text=txt, parent=cur))

        tag = expression[pos + 1 : end_pos]

        if tag.startswith("/"):
            assert tag[1:] == cur.tag, f"unexpected: </{tag}>"
            cur = cur.parent
        else:
            new_node = TagNode(tag=tag, parent=cur)
            cur.add_child(new_node)
            cur = new_node

        expression = expression[end_pos + 1 :]

    if expression:
        cur.add_child(TextNode(text=expression, parent=cur))

    return root


def print_tree(node: Node, current_color: str = "") -> None:
    color_codes = {
        "red": "\033[91m",
        "green": "\033[92m",
        "blue": "\033[94m",
        "reset": "\033[0m",
    }

    if isinstance(node, TagNode):
        current_color = color_codes.get(node.tag, current_color)
        for child in node.children:
            print_tree(child, current_color)
    elif isinstance(node, TextNode):
        reset = color_codes["reset"]
        print(f"{current_color}{node.text}{reset}", end="")


if __name__ == "__main__":
    import sys

    print_tree(parse_expression(sys.argv[1]))

Пример использования:

python parse_colors.py "<green>green text <blue>blue text</blue> <red>red text</red> another green text</green>"

Исправление rtxtxtrx, :

Честно говоря, то срань какая-то. Я про ту либу.

#!/usr/bin/env python
from __future__ import annotations

from dataclasses import dataclass, field


@dataclass
class Node:
    children: list[Node] = field(default_factory=list)
    parent: Node | None = None

    def add_child(self, child: Node) -> None:
        child.parent = self
        self.children.append(child)


@dataclass
class TagNode(Node):
    tag: str = ""


@dataclass
class TextNode(Node):
    text: str = ""


def parse_expression(expression: str) -> Node:
    pos = 0
    root = TagNode(tag="root")
    cur = root

    while ~(pos := expression.find("<")):
        end_pos = expression.find(">", pos + 1)

        if txt := expression[:pos]:
            cur.add_child(TextNode(text=txt, parent=cur))

        tag = expression[pos + 1 : end_pos]

        if tag.startswith("/"):
            assert tag[1:] == cur.tag, f"unexpected: </{tag}>"
            cur = cur.parent
        else:
            new_node = TagNode(tag=tag, parent=cur)
            cur.add_child(new_node)
            cur = new_node

        expression = expression[end_pos + 1 :]

    if expression:
        cur.add_child(TextNode(text=expression, parent=cur))

    return root


def print_tree(node: Node, current_color: str = "") -> None:
    color_codes = {
        "red": "\033[91m",
        "green": "\033[92m",
        "blue": "\033[94m",
        "reset": "\033[0m",
    }

    if isinstance(node, TagNode):
        current_color = color_codes.get(node.tag, current_color)
        for child in node.children:
            print_tree(child, current_color)
    elif isinstance(node, TextNode):
        reset = color_codes["reset"]
        print(f"{current_color}{node.text}{reset}", end="")


if __name__ == "__main__":
    import sys

    print_tree(parse_expression(sys.argv[1]))

Пример использования:

python parse_colors.py "<green>green text <blue>blue text</blue> <red>red text</red> another green text</green>"

Исходная версия rtxtxtrx, :

Честно говоря, то срань какая-то. Я про ту либу.

#!/usr/bin/env python
from __future__ import annotations

from dataclasses import dataclass, field


@dataclass
class Node:
    children: list[Node] = field(default_factory=list)
    parent: Node | None = None

    def add_child(self, child: Node) -> None:
        child.parent = self
        self.children.append(child)


@dataclass
class TagNode(Node):
    tag: str = ""


@dataclass
class TextNode(Node):
    text: str = ""


def parse_expression(expression: str) -> Node:
    pos = 0
    root = TagNode(tag="root")
    cur = root

    while ~(pos := expression.find("<")):
        end_pos = expression.find(">", pos + 1)

        if txt := expression[:pos]:
            cur.add_child(TextNode(text=txt, parent=cur))

        tag = expression[pos + 1 : end_pos]

        if tag.startswith("/"):
            assert tag[1:] == cur.tag, f"unexpected: <{tag}>"
            cur = cur.parent
        else:
            new_node = TagNode(tag=tag, parent=cur)
            cur.add_child(new_node)
            cur = new_node

        expression = expression[end_pos + 1 :]

    if expression:
        cur.add_child(TextNode(text=expression, parent=cur))

    return root


def print_tree(node: Node, current_color: str = "") -> None:
    color_codes = {
        "red": "\033[91m",
        "green": "\033[92m",
        "blue": "\033[94m",
        "reset": "\033[0m",
    }

    if isinstance(node, TagNode):
        current_color = color_codes.get(node.tag, current_color)
        for child in node.children:
            print_tree(child, current_color)
    elif isinstance(node, TextNode):
        reset = color_codes["reset"]
        print(f"{current_color}{node.text}{reset}", end="")


if __name__ == "__main__":
    import sys

    print_tree(parse_expression(sys.argv[1]))

Пример использования:

python parse_colors.py "<green>green text <blue>blue text</blue> <red>red text</red> another green text</green>"