[英]How to send iPython HTML class to a .html file?
我有一個對象, 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
帖子。 如果這是完全錯誤的方法,請告訴我。
好像你可以替換它
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以獲得更復雜的樣式。
我用我的校正測試了你的功能,保存了一個測試數據幀,它在我的瀏覽器中顯示為藍色表,如下所示,我相信它應該:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.