python - Python 将文本添加到使用 to_html() 方法生成的 HTML 表格文件文件中
问题描述
拜托我有一个可能很简单的问题,特别是对于那些 HTML 专家。我基本上有一个 python pandas 数据框'df',我使用有用的方法将它转换为 HTML 文档:
html = df.to_html()
text_file = open('example.html', "w")
text_file.write(html)
text_file.close()
我面临的问题是我需要在表格之前添加一个段落(一个简单的句子)。
我尝试将以下代码添加到我的脚本中:
title = """<head>
<title>Test title</title>
</head>
"""
html = html.replace('<table border="1" class="dataframe">', title + '<table border="1" class="dataframe">')
但它似乎没有做任何事情,而且实际上我需要添加的不是标题,而是包含段落信息的字符串。有没有人有一个不涉及使用漂亮汤或其他库的简单建议?谢谢你。
解决方案
这段代码几乎可以满足我的需要:
html = df.to_html()
msg = "custom mesagges"
title = """
<html>
<head>
<style>
thead {color: green;}
tbody {color: black;}
tfoot {color: red;}
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h4>
""" + msg + "</h4>"
end_html = """
</body>
</html>
"""
html = title + html + end_html
text_file = open(file_name, "w")
text_file.write(html)
text_file.close()
推荐阅读
- javascript - Uploading/viewing image in website not working
- c++ - public: static constant string declaraion/initialization issue
- uwp - How to autosave RichEditBox text?
- entity-framework-core - 审核对自有实体 Entity Framework Core 所做的更改
- typescript - 打字稿检查接口的泛型类型
- node.js - how to use aggreate query using in mongodb?
- python - 在 2D 数据上拟合抛物线——已编辑
- java - Java Runtime -ERR 'fsctl Command not found
- c# - String.Replace() 带有布尔值?
- php - 我如何从对象打印订阅