欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python URL和文件名互转

程序员文章站 2022-06-12 16:02:36
...
from typing import List, Tuple


class UrlUtil:
    """
    URL和文件名互转
    """

    # 正反替换器
    charInUrl:List[str]=[":","/","?","&"]
    charInFileName: List[str] = ["`", "#", "]", "$"]


    class Direction:
        def __init__(self, sourceCharList: List[str], targetCharList: List[str] ):
            self.sourceCharList : int = sourceCharList
            self.targetCharList : int = targetCharList

    DirectionUrlToFileName:Direction=Direction(charInUrl,charInFileName)

    DirectionFileNameToUrl: Direction = Direction(charInFileName,charInUrl)




    @staticmethod
    def _to(source:str, direction:Direction)->str:
        """
        :param source: 来源: url 或 fileName
        :param direction: 方向:   
        :return: 返回目标 : fileName或者url
        """
        target:str=source

        for k in range(len(direction.sourceCharList)):
            sourceChar=direction.sourceCharList[k]
            targetChar = direction.targetCharList[k]
            target=target.replace(sourceChar,targetChar)
        return target


    @staticmethod
    def urlToFileName(url:str)->str:
        """
        url转到文件名
        :param url:
        :return:
        """
        assert not UrlUtil._arrAHasArrBAnyElement(UrlUtil.charInFileName, url) , f"无法编码url,会混淆,编码后不能还原,{url},{UrlUtil.charInFileName}"
        return UrlUtil._to(url, UrlUtil.DirectionUrlToFileName)

    @staticmethod
    def _arrAHasArrBAnyElement(arrA:List[str], arrB:List[str]):
        for b in arrB:
            if b in arrA:
                return True
        return False

    @staticmethod
    def fileNameToUrl(fileName:str)->str:
        """
        文件名转url
        :param fileName:
        :return:
        """
        assert not UrlUtil._arrAHasArrBAnyElement(UrlUtil.charInUrl, fileName) , f"无法编码fileName,会混淆,编码后不能还原,{fileName},{UrlUtil.charInUrl}"
        return UrlUtil._to(fileName, UrlUtil.DirectionFileNameToUrl)



def UrlFileNameConvertTest():
    urlRight:str="https://wsy.com/market.htm?kid=1&cid=30"
    fileNameRight:str='https`##wsy.com#market.htm]kid=1$cid=30'

    fileNameReturn:str=UrlUtil.urlToFileName(urlRight)
    assert fileNameReturn==fileNameRight

    urlReturn: str = UrlUtil.fileNameToUrl(fileNameRight)
    assert urlReturn == urlRight

    end=True

UrlFileNameConvertTest()

源码链接

相关标签: python