【问题标题】:encoding url to short unique file name将 url 编码为唯一的短文件名
【发布时间】:2017-03-12 01:10:47
【问题描述】:

我想根据 url 将 html 保存到文件中。

要获得唯一的 url 名称,我正在使用 uuid。

>>> url = "https://www.google.co.in/?gfe_rd=cr&ei=-koUWPf4HqzT8ge2g6HoBg&gws_rd=ssl"
>>> uuidstring = str(uuid.uuid5(uuid.NAMESPACE_DNS, url))

但我想进一步缩短名称。有没有办法将字符串缩短为唯一的小字符串。

我尝试了base64,但我无法弄清楚。

>>> uuid.UUID(uuidstring).bytes.encode('base64').rstrip('=\n').replace('/', '_')
>>> AttributeError: 'bytes' object has no attribute 'encode'

相关问题:Convert UUID 32-character hex string into a "YouTube-style" short id and back

【问题讨论】:

    标签: python


    【解决方案1】:

    像这样使用base64模块,它可以处理二进制数据,然后像ascii一样进行解码(因为base64是ascii,所以可以)。

    import uuid,base64
    
    url = "https://www.google.co.in/?gfe_rd=cr&ei=-koUWPf4HqzT8ge2g6HoBg&gws_rd=ssl"
    uuidstring = str(uuid.uuid5(uuid.NAMESPACE_DNS, url))
    z=base64.encodebytes(uuid.UUID(uuidstring).bytes).decode("ascii").rstrip('=\n').replace('/', '_')
    print(z)
    

    结果:

    pvEA9qOdX8COYyJf8zgzRA
    

    【讨论】:

    • 是否需要.replace('/', '_')?将uuidstring转换为base64时会出现'/'吗?
    • 有可能得到/,例如base64.encodebytes(b"???")。您可能需要删除另一个字符:+。但是对于您的字符串a6f100f6-a39d-5fc0-8e63-225ff3383344,您不太可能是对的,因为您需要很多后续的 1 位。
    • 谢谢。我将检查大型数据集并进行相应更新。
    猜你喜欢
    • 2014-09-16
    • 1970-01-01
    • 2010-09-20
    • 2011-08-03
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2011-10-21
    相关资源
    最近更新 更多