0

Есть небольшая задачка. вот код:

class Tag:
    def __init__(self, tag, is_single=False):
        self.tag = tag
        self.text = ""
        self.attributes = {}

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        attrs = []
        for attribute, value in self.attributes.items():
            attrs.append('%s="%s"' % (attribute, value))
        attrs = " ".join(attrs)

        if self.is_single:
            print("<{tag} {attrs}/>".format(tag=self.tag, attrs=attrs))
        else:
            print(
                "<{tag} {attrs}>{text}</{tag}>".format(
                    tag=self.tag, attrs=attrs, text=self.text
                )
            )

    def __str__(self):
        attrs = []
        for attribute, value in self.attributes.items():
            attrs.append('%s="%s"' % (attribute, value))
        attrs = " ".join(attrs)

        return "<{tag} {attrs}>{text}</{tag}>".format(tag=self.tag, attrs=attrs, text=self.text)

class HTML(Tag, TopLevelTag):




class TopLevelTag:
    def __init__(self, tag, toplevel=False, is_single=False):
        self.tag = tag
        self.text = ""
        self.attributes = {}

        self.toplevel = toplevel
        self.is_single = is_single
        self.children = []

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.toplevel:
            print("<%s>" % self.tag)
            for child in self.children:
                print(child)

            print("</%s>" % self.tag)

    def __str__(self):
        attrs = []
        for attribute, value in self.attributes.items():
            attrs.append('%s="%s"' % (attribute, value))
        attrs = " ".join(attrs)

        if self.children:
            opening = "<{tag} {attrs}>".format(tag=self.tag, attrs=attrs)
            internal = "%s" % self.text
            for child in self.children:
                internal += str(child)
            ending = "</%s>" % self.tag
            return opening + internal + ending
        else:
            if self.is_single:
                return "<{tag} {attrs}/>".format(tag=self.tag, attrs=attrs)

            else:
                return "<{tag} {attrs}>{text}</{tag}>".format(tag=self.tag, attrs=attrs, text=self.text)


if __name__ == "__main__":

    with HTML(output="index.html") as doc:
        with TopLevelTag("head") as head:
            with Tag("title") as title:
                title.text = "hello"
                head += title
            doc += head

        with TopLevelTag("body") as body:
            with Tag("h1", klass=("main-text",)) as h1:
                h1.text = "Test"
                body += h1

            with Tag("div", klass=("container", "container-fluid"), id="lead") as div:
                with Tag("p") as paragraph:
                    paragraph.text = "another test"
                    div += paragraph

                with Tag("img", is_single=True, src="/icon.png") as img:
                    div += img

                body += div
            doc += body

должно получиться что-то вроде:

<html>
<head>
  <title>hello</title>
</head>
<body>
    <h1 class="main-text">Test</h1>
    <div class="container container-fluid" id="lead">
        <p>another test</p>
        <img src="/icon.png" data-image="responsive"/>
    </div>
</body>
</html>

часть я уже написал, но ещё не известно правильно или нет, т.к. немогу оформить сохранение файла в html в классе HTML... ПАМАГИТЕ...

2
  • В __init__ добавить параметр file и передавать его потом во все print
    – insolor
    12 авг 2019 в 18:23
  • А можно по подробнее?
    – Evgeny
    13 авг 2019 в 3:50

1 ответ 1

0

У функции print есть параметр "file", который позволяет делать вывод не в консоль, а в файл. Пример:

with open('file.txt', 'wt') as file:
    print('Hello!', file=file)

В вашем случае нужно добавить чтобы файл передавался при создании объекта и передавался в print-ы (нужно добавить file=self.file во все print-ы):

import sys

...
class Tag:
    def __init__(self, tag, is_single=False, file=sys.stdout):
        self.file = file

    ...

    def __exit__(self, *args, **kwargs):
        ...
            print("<{tag} {attrs}/>".format(tag=self.tag, attrs=attrs), file=self.file)

Работать будет примерно так:

with open('file.html', 'wt') as file:
    with Tag('html', file=file):
        pass

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.