首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将iPython HTML类发送到.html文件?

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

Stack Overflow用户
提问于 2018-07-25 03:19:16
回答 1查看 1.4K关注 0票数 3

我有一个对象class 'IPython.core.display.HTML,并且我试图将它保存为一个.html文件。我该怎么做呢?

代码语言:javascript
复制
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()参数必须是字符串,而不是None

编辑:注意,I'm not using IPython/Jupyter。我只是想添加一些CSS到我的文件中,然后发现了那篇HTML_with_style文章。如果这是完全错误的方式,请让我知道。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-25 04:24:51

看起来你可以取代

代码语言:javascript
复制
return HTML(style + df_html)

使用

代码语言:javascript
复制
return style + df_html

并执行以下操作:

代码语言:javascript
复制
with open('/path/to/file.html', 'w') as f:
    f.write(HTML_with_style(df))

但是,也许您应该研究一下https://pandas.pydata.org/pandas-docs/stable/style.html,以获得更复杂的样式。

我用我的修正测试了你的函数,保存了一个测试数据帧&它在我的浏览器中显示为一个蓝色的表格,如下所示,我认为它应该是这样的:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51506095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档