代码之家  ›  专栏  ›  技术社区  ›  BruceWayne

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

  •  3
  • BruceWayne  · 技术社区  · 6 年前

    我有个东西, 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()参数必须是str,而不是None

    编辑:注意,我 使用IPython/Jupyter。我只是想在我的HTML文件中添加一些CSS,结果发现 HTML_with_style 邮政。如果这是完全错误的做法,请让我知道。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Haleemur Ali    6 年前

    看来你可以替换

    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