我有一个对象,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
帖子。 如果这是完全错误的方法,请告诉我。