【问题标题】:Manipulate url to return length of string/number after special characters处理 url 以在特殊字符后返回字符串/数字的长度
【发布时间】:2021-05-27 20:43:58
【问题描述】:

给定一个 URL,我希望能够获取每个特殊字符之后的字符数(s 如果非数字字符,d 表示数字字符)。例如,对于这样的 URL:

url="https://imag9045.pexels1.pre45p.com/photos/414612/pexels-photo-414612.jpeg"

我希望输出为:'4s.4d.6s.1d.4s.2d.com/6s/6d/6s-5s-6d.'

我下面的代码仅在域之前(“.com”之前)生成所需的结果。我在生成其余部分时遇到问题。

     How can I manipulate it to get the desired output (`'4s.4d.6s.1d.4s.2d.com/6s/6d/6s-5s-6d.'`)? 

【问题讨论】:

    标签: python python-3.x string urlparse


    【解决方案1】:

    您需要循环每个字符,如

    import string
    def mysplit(path):
        s=d=0
        out=''
        for c in path:
            if c in string.punctuation:
                if s:
                    out += f'{s}s'
                    s=0
                if d:
                    out += f'{d}d'
                    d=0
                out += c
            elif c in string.digits:
                d+=1
            else:
                s+=1
        if s:
            out += f'{s}s'
        if d:
            out += f'{d}d'
        return out
    
    >>> mysplit('/photos/414612/pexels-photo-414612.jpeg')
    '/6s/6d/6s-5s-6d.4s'
    

    上述函数除了处理顶级域名外,还可以用于url的第一部分

    >>> mysplit('https://imag9045.pexels1.pre45p.com')
    '5s://4s4d.6s1d.4s2d.3s'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2010-11-19
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多