pandas .to_html 的换行符?

问题描述 投票:0回答:2

我正在编写一个需要将数据帧转换为 html 表的脚本。到目前为止一切都很好,除了当我查看输出时无法识别换行符。

例如字符串

"Hello < br > World"
"Hello \n World"
将仅按所示输出,而不带有换行符。

是否有任何我不知道的解决方法或特殊键可以在 pandas html 表中创建换行符?

< br > 包括空格,因为它顺便在此页面上创建了一个实际的断点。

谢谢你:)

python html pandas dataframe
2个回答
1
投票

您可以使用

render
df.style.format
在数据框中应用所需的更改:

import pandas as pd

data = {'Text': ["Hello <br> World", "Hello \n World"]}
df = pd.DataFrame(data)

def add_line_breaks(text):
    return text.replace('\n', '<br>')

df_styled = df.style.format({'Text': add_line_breaks})

html_table = df_styled.render()

with open('output.html', 'w') as file:
    file.write(html_table)

输出:


0
投票

将字符串中的所有“/n”转换为“< br >”。然后使用 to_html(escape=False) 对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.