Question:
How to implement plain text to HTML converter in Python?

Problem:

I'm trying to implement a simple "plain text to html" converter, but can't figure out why it doesn't work as intended. So here's what I want to do - let's say we have a text: text = 'Hey! /n/nIt was really nice to meet you! /n/nOur team hopes to see you soon! /n/n/nBest regards, /nYour new team.' So for such text, what I want to do is:


  1. Wrap all the text inside the <p></p> tags

  2. Each line should be wrapped into <p></p> tags

  3. If there's only a single /n that means that this is a new line and we just have to wrap it into p tags

  4. but if there are multiple /n then each /n starting from 2nd should be replaced as <br> tag, and then for the last /n just wrap a line into p (see point 2)

here's the code i've made for now:


def convert_text_to_html(text):

    # Split the text into lines using /n as the delimiter

    lines = text.split('/n')


    # Initialize an empty new_lines_replaced string

    new_lines_replaced = ''


    for line in lines:

        # Initialize a count to keep track of consecutive /n

        count = 0


        # Check for consecutive /n characters at the beginning of the line

        while line.startswith('/n'):

            count += 1

            line = line[2:]


        # Add the corresponding number of <br> tags

        br_tags = '<br class="ProseMirror-trailingBreak">' * count


        # Wrap the line in <p> tags

        new_lines_replaced += f'{br_tags}<p>{line}</p>'


    # Wrap the entire string with <p> and </p> tags

    return f'<p>{new_lines_replaced}</p>'



but instead it returns only p tags and no br tags, here's the output: <p><p>Hey! </p><p></p><p>It was really nice to meet you! </p><p></p><p>Our team hopes to see you soon! </p><p></p><p></p><p>Best regards, </p><p>Mojob team.</p></p>

UPD: alright guys, thanks to all of you, but i decided to move forward with empty <p></p> tags instead of <br> ones, so found a solution to work this way:


def convert_text_to_html(text):

    # replace each `\n` with empty <p> tag - it closes the previous one and opens a new one

    new_lines_replaced = text.replace('\n', '</p><p>')


    # add initial <p> tag for the first line

    new_lines_replaced = f'<p>{new_lines_replaced}'


    return f'<p>{new_lines_replaced}</p>'



Solution:

You're trying to check if the line starts with a /n, this will never be true since str.split(x) splits the str at all occurrences of x and removes x from the str. Also you don't need to check for /ns in the for loop since every line is indeed a new line.

And you're getting empty <p></p> because you don't check if the line is empty or not


Here is the improved code:


def convert_text_to_html(text):

    # Split the text into lines using /n as the delimiter

    lines = text.split('/n')

    

    # Initialize an empty new_lines_replaced string

    new_lines_replaced = ''

    

    for line in lines:

        if not line == lines[0]:  # Check if this is the first iteration, since we don't want an unwanted br at the start of the html

            # Add <br> tag

            new_lines_replaced += '<br class="ProseMirror-trailingBreak" />'

        

        # Now the line can be empty since /n/n exits and that would lead to [..., "", ...] when split

        # So we need to check if the line is not empty

        if line.strip():  # .strip because there can be spaces between /n's and that would make line true since it's not empty

            new_lines_replaced += f"<p>{line}</p>"

    

    # Wrap the entire string with <div> and </div> tags (Since wrapping <p> inside a <p> is semantically wrong)

    return f'<div>{new_lines_replaced}</div>'


Suggested blogs:

>How can I browser to render links in streamed content in Django?

>Access the "model" attribute for a ListView in Django for template

>How to use a function to print S3 data to HTML using Django?

>How to make a code executed after an entry is inserted, removed or updated?

>How to insert new data into the table in Django?

>Disabling default ordering in the Django admin panel

>How to migrate `DateTimeField` to `DateField` in Django?


Ritu Singh

Ritu Singh

Submit
0 Answers