Python动态构造变量名,实现html多个占位符替换
在Python中,变量名一般都是写定的,但如果有需求,需要我们动态构造多个有规律的变量名,来将我们的值传给构造好的变量名,那该怎么办呢?
初始html:
本篇将以替换html占位符作为例子,进行动态构造变量名的实例。
为了有更好的参考意义,我简单写了两种占位符替换情况:不加标签 and 加标签,可以自行选择。
将上面各列数据换为占位符后的html:
html代码如下
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Demo</title>
</head>
<body>
<h1>Demo</h1>
<table>
<tr>
<th>{title_1}</th>
<th>{title_2}</th>
<th>{title_3}</th>
</tr>
<tr>
<!--<td>Data 1A</td>-->
<!--<td>Data 2A</td>-->
<!--<td>Data 3A</td>-->
{data_1}
</tr>
<tr>
<!--<td>Data 1B</td>-->
<!--<td>Data 2B</td>-->
<!--<td>Data 3B</td>-->
{data_2}
</tr>
<tr>
<!--<td>Data 1C</td>-->
<!--<td>Data 2C</td>-->
<!--<td>Data 3C</td>-->
{data_3}
</tr>
<!-- 可以添加更多数据行 -->
</table>
</body>
<style>
h1 {
text-align: center;
}
table {
border-collapse: collapse;
width: 100%;
}
table, th, td {
border: 1px solid #ccc;
}
th, td {
padding: 10px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</html>
文本keywords.txt存储列数据
张三 19 北京
李四 20 上海
王五 21 广州
Python代码如下:
# -*- coding: utf-8 -*-
# @Time : 2023/10/14 23:35
# @Author : Ztop
# @Email : top.zeker@gmail.com
# @Link: https://www.zeker.top
from bs4 import BeautifulSoup, NavigableString
import html
class Work(object):
def __init__(self):
# 初始化
self.html_file = "demo.html"
self.each_placeholder_number = 3
self.placeholder_dict = {'title_placeholder': 'title_', 'data_placeholder': 'data_'}
self.title_data = ["姓名", "年龄", "所在地"]
self.output_file = "output.html"
with open("keywords.txt", 'r', encoding='utf-8') as f:
content = f.read()
# 按空格分割内容
words = content.split()
self.html_list = []
new_td_list = []
count = 0
for word in words:
new_td = ('<td>' + word + '</td>') # 生成新的html
new_td_list.append(new_td)
count += 1
if count == self.each_placeholder_number:
new_td_str = "".join(new_td_list)
self.html_list.append(new_td_str)
count = 0
new_td_list = []
def processor(self):
# 读取模板 HTML 文件
with open(self.html_file, 'r', encoding='utf-8') as f:
# 使用BeautifulSoup提取纯文本部分
soup = BeautifulSoup(f.read(), 'html.parser')
# 遍历placeholder_dict
for k, v in self.placeholder_dict.items():
for number in range(self.each_placeholder_number):
var = v + str(number + 1) # 对占位符格式进行拼接
if k == 'title_placeholder': # 如果是标题占位符则取标题列表
value = self.title_data[number]
else:
value = self.html_list[number]
for tag in soup.find_all(string=lambda text: isinstance(text, str)):
if var in tag:
if isinstance(tag, NavigableString):
# 如果是NavigableString,将其转换为包含变量值的字符串
new_string = str(tag).format(**{var: value})
tag.replace_with(new_string)
else:
# 否则,标签是一个标签元素,可以安全使用get_text()
tag_string = tag.get_text()
tag.replace_with(tag_string.format(**{var: value}))
break # 跳出内循环
with open(self.output_file, "w", encoding="utf-8") as f:
f.write(html.unescape(str(soup)))
print(f"已生成{self.output_file}!!!")
if __name__ == '__main__':
work = Work()
work.processor()
最终效果
如果我的文章对你有帮助的话,也可以给我点点赞,关注一下我!
之后可能也会推出一些实用的程序,欢迎给我留言。