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

标签 python python-3.x pandas ipython

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

def HTML_with_style(df, style=None, random_id=None):
    # https://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style/38511805#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))

但是我明白了

TypeError: write() argument must be str, not None

编辑:请注意,我使用 IPython/Jupyter。我只是想在我的 HTML 文件中添加一些 CSS,然后发现 HTML_with_style 帖子。如果这是完全错误的解决方法,请告诉我。

最佳答案

看来你可以替换

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

关于python - 如何将 iPython HTML 类发送到 .html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51506095/

相关文章:

Python - 在上传 S3 图像时将其公开?

python - 如何使用xlrd写入excel文件

Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住

python - Pandas 两列的条件滚动总和

python - 在 Pandas 中创建 DateTimeIndex

python - 在 Pandas 中一次在列中显示常用值

python - 从 Shapely 中的多边形中提取点/坐标

python - 我在 Heroku 上收到 404 错误,但它在本地有效

python - tensorflow 中具有权重衰减参数的 SGD

python - 在python中执行查询之前设置游标对象的限制