You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python纯文本转HTML转换器实现问题及替代方案

纯文本转HTML转换器问题及解决

测试文本:

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.'

需求

  • 将所有文本包裹在<p></p>标签内
  • 每行用<p></p>标签包裹
  • 单个/n表示换行,仅用p标签包裹对应内容
  • 多个/n时,从第二个开始替换为<br>标签,最后一个/n对应换行仍用p标签包裹

最初代码及问题

最初编写的代码如下:

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 = '&lt;br class=&quot;ProseMirror-trailingBreak&quot;&gt;' * count

        # Wrap the line in <p> tags
        new_lines_replaced += f'{br_tags}&lt;p&gt;{line}&lt;/p&gt;'

    # Wrap the entire string with <p> and </p> tags
    return f'&lt;p&gt;{new_lines_replaced}&lt;/p&gt;'

这段代码仅返回<p>标签,未生成<br>标签,输出结果:

&lt;p&gt;&lt;p&gt;Hey! &lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;It was really nice to meet you! &lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;Our team hopes to see you soon! &lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;Best regards, &lt;/p&gt;&lt;p&gt;Mojob team.&lt;/p&gt;&lt;/p&gt;

最终解决方案

最终决定用空<p></p>标签替代<br>标签,解决方案代码如下:

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', '&lt;/p&gt;&lt;p&gt;')

    # add initial <p> tag for the first line
    new_lines_replaced = f'&lt;p&gt;{new_lines_replaced}'

    return f'&lt;p&gt;{new_lines_replaced}&lt;/p&gt;'

内容的提问来源于stack exchange,提问作者Anna Kabatova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:55:35