将 url 编码为简短的唯一文件名

Rah*_*hul 4 python

我想根据 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))
Run Code Online (Sandbox Code Playgroud)

但我想进一步缩短名称。有什么方法可以将字符串缩短为唯一的小字符串。

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

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

链接问题:将 UUID 32 个字符的十六进制字符串转换为“YouTube 风格”的短 ID 并返回

Jea*_*bre 5

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)
Run Code Online (Sandbox Code Playgroud)

结果:

pvEA9qOdX8COYyJf8zgzRA
Run Code Online (Sandbox Code Playgroud)