在python中从列表创建html表

时间:2018-01-30 14:12:42

标签: python html python-3.x

我正在尝试将列表(从文本文件)转换为html表格代码以插入html文件中。我成功地将jinja2用于将html文件中的关键字替换为我之前创建的html表代码的部分。问题是在html文件中,所有新表标签都被更改为&lt;tr&gt;&lt;td&gt;,它应该是<tr><td>等。这是我使用的代码:

from bs4 import BeautifulSoup
import re
from os.path import abspath
import plistlib
from jinja2 import Template
from collections import Counter



my_plist = plistlib.readPlist("iphone_data/app_info.plist")
iphone_version = my_plist["CFBundleShortVersionString"]
changelog = open("changelog.txt", "r", encoding='utf-8')
list1 = changelog.readlines()
template = Template("""
    {% for item, count in bye.items() %}
         <tr><td>{{item}}</td></tr>
    {% endfor %}
""")
log = template.render(bye=Counter(list1))
file = abspath('iphone_data/letter.html')
html = open(file, 'r', encoding="utf-8")
soup = BeautifulSoup(html, "html.parser")
target = soup.find_all(text=re.compile(r'wersja_1'))
changes = soup.find_all(text=re.compile(r'changelog'))
for v in target:
    v.replace_with(v.replace('wersja_1', iphone_version))
for c in changes:
    c.replace_with(c.replace('changelog', log))

html = soup.prettify("utf-8")
with open("iphone_data/letter_mod.html", "wb") as file:
    file.write(html)

我还从plist文件中替换了版本读取,但这完美无缺。正确的代码应该如何防止这种情况发生?

2 个答案:

答案 0 :(得分:1)

尝试替换

html = soup.prettify("utf-8")

html = soup.prettify("utf-8", formatter=None)

<强> More Info

答案 1 :(得分:0)

Flask模块只适用于表格:“flask_table”。这里提供的文档:http://flask-table.readthedocs.io/en/stable/,您可以将表中的项目定义为数组或字典,并以这种方式处理它们:

#load items from your database with something like
items = ItemModel.query.all()
# Populate the table
table = ItemTable(items)

# Print the html
print(table.__html__())
# or just {{ table }} from within a Jinja template