Python-MjUtil

Python基础工具类:

  • 判断字符串/列表/字典/元组是否为空
  • 返回非None字符串
  • 向模板中写入数据,占位符${name},我叫${name}->我叫michael
  • 根据模板读取数据,占位符${name},写入数据函数的逆操作
  • (私有)获取模板中的占位符${name}和字段名name
  • (私有)根据分隔符分割模板
"""
@Title: 基础工具类
@Time: 2024/2/9
@Author: Michael Jie
"""

import re


class MjUtil:
    # 数字
    figures = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    # 字母
    letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
               "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
               "U", "V", "W", "X", "Y", "Z"]

    # 判断字符串/列表/字典/元组是否为空
    @staticmethod
    def is_none(obj: str | list | dict | tuple) -> bool:
        """
        :param obj: 字符串/列表/字典/元组
        :return: bool
        """
        result = False
        if obj is not None:
            name = type(obj).__name__
            # 字符串," "/""/"None"
            if name == "str":
                result = True if obj.isspace() or obj == "" or obj == "None" else False
            # 列表[],字典{},元组()
            elif name == "list" or name == "dict" or name == "tuple":
                result = True if len(obj) == 0 else False
        else:
            result = True
        return result

    # 返回非None字符串
    @staticmethod
    def to_not_none(text: str) -> str:
        """
        :param text: 字符串
        :return: str
        """
        return "" if MjUtil.is_none(text) else text

    # 向模板中写入数据,占位符${name},我叫${name}->我叫michael
    @staticmethod
    def write_data(temp: str,
                   data: dict,
                   clear_temp: bool = True) -> str:
        """
        :param temp: 模板字符串,"我叫${name}"
        :param data: 数据,{"name": "michael"}
        :param clear_temp: 是否清除空值占位符
        :return: str,"我叫michael"
        """
        if MjUtil.is_none(temp):
            return ""
        # 获取占位符和字段名
        tags, fields = MjUtil.__get_tag_and_field(temp)
        if MjUtil.is_none(tags) or MjUtil.is_none(fields):
            return temp
        # 替换占位符,写入数据
        for index, tag in enumerate(tags):
            field = fields[index]
            # 判断是否存在字段
            if field in data.keys():
                value = data.get(field)
                # 当数据为空时,是否删除占位符
                if MjUtil.is_none(value) and not clear_temp:
                    continue
                temp = temp.replace(tag, str(MjUtil.to_not_none(value)))
        return temp

    # 根据模板读取数据,占位符${name},写入数据函数的逆操作
    @staticmethod
    def read_data(temp: str,
                  text: str,
                  data: dict = None) -> dict:
        """
        :param temp: 模板字符串,"我叫${name}"
        :param text: 数据字符串,"我叫michael"
        :param data: 数据,{}
        :return: dict,{"name": "michael"}
        """
        if data is None:
            data = {}
        # 获取占位符和字段名
        tags, fields = MjUtil.__get_tag_and_field(temp)
        if MjUtil.is_none(tags) or MjUtil.is_none(fields):
            return data
        # 将模板字符串拆分,[xx, ${name1}, xxx, ${name2}, ${name3}, xx]
        strings = MjUtil.__split_by_tag(temp, tags)
        if len(strings) == len(tags):
            data[fields[0]] = text
            return data
        # 循环对比,提取数据
        for index, tag in enumerate(tags):
            inx = strings.index(tag)
            # 分首位、中间、末尾处理
            if inx == 0:
                end = strings[inx + 1]
                lst = re.findall("^.*" + end, text)
                value = "" if MjUtil.is_none(lst) else lst[0].replace(end, "")
            elif inx == len(strings) - 1:
                start = strings[inx - 1]
                lst = re.findall(start + ".*$", text)
                value = "" if MjUtil.is_none(lst) else lst[0].replace(start, "")
            else:
                start = strings[inx - 1]
                end = strings[inx + 1]
                lst = re.findall(start + r".*" + end, text)
                value = "" if MjUtil.is_none(lst) else lst[0].replace(start, "").replace(end, "")
            data[fields[index]] = value
        return data

    # 获取模板中的占位符${name}和字段名name
    @staticmethod
    def __get_tag_and_field(text: str) -> tuple:
        """
        :param text: 模板字符串,"我叫${name}"
        :return: tuple,([${name}], [name])
        """
        # 获取占位符,[${name1}, ${name2}, ${name3}]
        tag_list = re.findall(r"\${\w+}", text)
        if MjUtil.is_none(tag_list):
            return None, None
        # 获取字段,[name1, name2, name3]
        field_list = []
        for tag in tag_list:
            field = re.findall(r"{(.*?)}", tag)
            if MjUtil.is_none(field):
                tag_list.remove(tag)
                continue
            field_list.append(field[0])
        return tag_list, field_list

    # 根据分隔符分割模板
    @staticmethod
    def __split_by_tag(text: str,
                       tags: list[str]) -> list[str]:
        """
        :param text: 需要被分割的字符串,"我叫${name},今年已经${age}岁了。"
        :param tags: 分隔符列表,["${name}", "${age}"]
        :return: list[str],["我叫", "${name}", ",今年已经", "${age}", "岁了。"]
        """
        lst = []
        # 分割字符串
        for i, tag in enumerate(tags):
            if tag not in text:
                continue
            strings = text.split(tag)
            lst.append(strings[0])
            lst.append(tag)
            text = strings[1]
            # 处理末尾字符串
            if i == len(tags) - 1:
                lst.append(strings[1])
        # 清除前后的空字符
        if lst[0] is None or lst[0] == "":
            del lst[0]
        if lst[-1] is None or lst[-1] == "":
            del lst[-1]
        return lst

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值