Python动态构造变量名,实现html占位符替换

本文介绍了在Python中动态构造变量名,以实现HTML多个占位符替换的方法。以替换HTML占位符为例,给出了不加标签和加标签两种占位符替换情况,还展示了HTML代码、存储列数据的文本文件及Python代码和最终效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

最终效果
在这里插入图片描述
如果我的文章对你有帮助的话,也可以给我点点赞,关注一下我!
之后可能也会推出一些实用的程序,欢迎给我留言。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月时下AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值