在熊猫数据框上显示 html 字符串值

时间:2021-05-22 09:07:03

标签: python html pandas string escaping

假设我有一个包含一些 HTML 的字符串值的数据框

my_dict = {"a":{"content":"""
<p>list of important things</p>
<ul>
<li>c</li>
<li>d</li>
</ul>
"""}}

df = pd.DataFrame.from_dict(my_dict,orient='index')

结果在意料之中:

我想将数据框导出为 HTML,以便我的 HTML 字符串在表格单元格内工作。

我的尝试

我知道 DataFrame.to_html(escape=False),它产生:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>content</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>a</th>
      <td>\n<p>list of important things</p>\n<ul>\n<li>c</li>\n<li>d</li>\n</ul>\n</td>
    </tr>
  </tbody>
</table>

看起来不对:

enter image description here

因为 HTML 有一个字面量 \\n,所以我认为该方法在将字符串值插入到数据集的 HTML 转换中时采用了字符串值的 repr

知道我可以再次将转义的 \\n 替换为 \n,这看起来应该是:

enter image description here

但我想知道是否有某种方法可以告诉 Pandas 将数据帧的文字字符串值插入到 HTML 中,而不是将 repr 插入到 HTML 中。我不明白 .to_html() 的一半 kwargs,所以我不知道这是否可能。

1 个答案:

答案 0 :(得分:2)

<块引用>

我想将数据框导出为 HTML,这样我的 HTML 字符串 在表格单元格内工作。

如果是这样,您可能需要考虑将 \n 替换为 HTML 换行符,即。 <br> 如果你想为它换行,或者你可以用一个空字符串替换它。

df['content'] = df['content'].str.replace('\n', '<br>')
df.to_html('html.html', escape=False)

如果您不想替换数据帧本身,您可以通过将其作为格式化程序传递来让 Pandas 处理它:

df.to_html('html.html', 
           formatters = {'content': lambda k: k.replace('\n', '<br>')}, 
           escape=False)

如果你只是完全想摆脱新行,你可以用空字符串替换它,无论是在数据帧本身还是作为格式化程序传递。

df.to_html('html.html', 
           formatters = {'content': lambda k: k.replace('\n', '')}, 
           escape=False)
相关问题