简体   繁体   English

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

[英]How to send iPython HTML class to a .html file?

I have an object, class 'IPython.core.display.HTML , and I'm trying to save this as a .html file. 我有一个对象, class 'IPython.core.display.HTML ,我试图将其保存为.html文件。 How can I do that? 我怎样才能做到这一点?

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))

But I get 但我明白了

TypeError: write() argument must be str, not None TypeError:write()参数必须是str,而不是None

Edit: Note, I'm not using IPython/Jupyter. 编辑:注意,我没有使用IPython / Jupyter。 I'm just trying to add some CSS to my HTML file, and found that HTML_with_style post. 我只是想在我的HTML文件中添加一些CSS,并发现HTML_with_style帖子。 If this is the completely wrong way to go about this, please let me know. 如果这是完全错误的方法,请告诉我。

it seems like you could replace 好像你可以替换它

return HTML(style + df_html)

with

return style + df_html

and do the following: 并执行以下操作:

with open('/path/to/file.html', 'w') as f:
    f.write(HTML_with_style(df))

But, maybe you should look into https://pandas.pydata.org/pandas-docs/stable/style.html for more complex styling. 但是,也许您应该查看https://pandas.pydata.org/pandas-docs/stable/style.html以获得更复杂的样式。

I tested your function with my correction, saved a test dataframe & it shows up as a blue table in my browser like below as i believe it should: 我用我的校正测试了你的功能,保存了一个测试数据帧,它在我的浏览器中显示为蓝色表,如下所示,我相信它应该:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM