如何将iPython HTML类发送到.html文件?

3

我有一个对象,class 'IPython.core.display.HTML',我想将其保存为.html文件。我该怎么做?

def HTML_with_style(df, style=None, random_id=None):
    # https://dev59.com/t1kT5IYBdhLWcg3wfvmo#38511805
    from IPython.display import HTML
    import numpy as np
    import re

    df_html = df.to_html()

    if random_id is None:
        random_id = 'id%d' % np.random.choice(np.arange(1000000))

    if style is None:
        style = """
        <style>
            table#{random_id} {{color: blue}}
        </style>
        """.format(random_id=random_id)
    else:
        new_style = []
        s = re.sub(r'</?style>', '', style).strip()
        for line in s.split('\n'):
                line = line.strip()
                if not re.match(r'^table', line):
                    line = re.sub(r'^', 'table ', line)
                new_style.append(line)
        new_style = ['<style>'] + new_style + ['</style>']

        style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

    return HTML(style + df_html)


new_df = HTML_with_style(df) # df is a Pandas DataFrame
f = open("test.html", 'w')
f.write(display(new_df))

但是我遇到了

类型错误:write()参数必须是str,而不是None

编辑:请注意,我没有使用IPython / Jupyter。 我只是尝试向我的HTML文件添加一些CSS,并发现了HTML_with_style帖子。 如果这是完全错误的方法,请告诉我。

1个回答

2
似乎您可以更换
return HTML(style + df_html)

使用

return style + df_html

并执行以下操作:
with open('/path/to/file.html', 'w') as f:
    f.write(HTML_with_style(df))

但是,也许你应该查看https://pandas.pydata.org/pandas-docs/stable/style.html了解更复杂的样式。

我使用您的更正测试了您的函数,并保存了一个测试数据框,如下图所示,它在我的浏览器中显示为蓝色表格,我认为它应该是这样的:

enter image description here


哇塞,这个可行!聪明的想法。另外,感谢提供Pandas链接。看起来有点复杂,但我一定会学习它,这样我就不必使用(在我看来)这种笨拙的方法了。 - BruceWayne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接