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 = '<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>'
这段代码仅返回<p>标签,未生成<br>标签,输出结果:
<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>
最终解决方案
最终决定用空<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', '</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>'
内容的提问来源于stack exchange,提问作者Anna Kabatova
相关产品推荐
相关产品推荐

