如何以无损方式缩短文本
How can I shorten text in a lossless way
我有一段文字要放入我的 URL,例如:
Put all speaking her delicate recurred possible. Set indulgence inquietude discretion insensible bed why announcing. Middleton fat two satisfied additions. So continued he or commanded household smallness delivered. Door poor on do walk in half. Roof his head the what.
但我希望它更短,例如这样的字符串:
kdghdsvvw564645b7573b4657435
我该怎么做?
您可以尝试 smaz 压缩短字符串。您需要连接到 C 代码或重新实现算法。
除了实施或使用压缩算法外,您还需要确保字符对于 URL 是安全的。例如,如果压缩算法压缩为二进制(大多数情况下都是这样做的),那将不适用于 URL。使用一种压缩算法后,需要实现另一种算法,将压缩后的数据转换为url-safe字符串。一些 JavaScript 压缩库,如 lz-string 提供了方便的功能,可以直接压缩或解压缩 URI-safe 文本。
答案取决于您是否要从 URL 字符串中恢复原始文本。
如果要恢复,请先使用无损方法压缩文本,例如建议使用 zlib 库或 smaz 压缩小文本。然后将压缩的二进制输出转换为 URL 安全格式。 Base64 就是这样一种方法。最终字符串可能更短或更长,具体取决于文本的可压缩性。
如果您不想恢复原始文本,只需使用 sha1sum 对您的文本进行哈希处理,然后在您的 URL 字符串中使用它的输出。散列对于两个不同的输入字符串将是唯一的。这是一个例子
~$ cat junk
Put all speaking her delicate recurred possible. Set indulgence inquietude discretion insensible bed why announcing. Middleton fat two satisfied additions. So continued he or commanded household smallness delivered. Door poor on do walk in half. Roof his head the what.
~$ sha1sum junk
e2acae1ae295de73541cd321da268a8d2d48ca7b junk
~$ gzip junk
~$ base64 junk.gz
H4sICFtXTF8AA2p1bmsAHU9LbgMxCN33FO8Ec4puK1XtCYhhYhQPTA3uqLcvyQbB0/vxuRI0BuIU
eqjd0WWCZWijFExpa05hnB6htyEbviWhxmvcxZrU+rNUcrGANdqUVLdCQ+wlwK3UV/8DmfmyVhEb
PpR5SBZxp0RejqDU2LW4xKxPj6goR3NLtVV4F/is+zjI+Hn7Cuk+GHHUAyYRr96/Un03vHuxz+eo
FHZcNB5VC53GvuHLfUfXKFdiZHlfnXJ7+wdZzrQRDgEAAA==
然后,使用 base64 -d 从 URL
中恢复原始文本
我有一段文字要放入我的 URL,例如:
Put all speaking her delicate recurred possible. Set indulgence inquietude discretion insensible bed why announcing. Middleton fat two satisfied additions. So continued he or commanded household smallness delivered. Door poor on do walk in half. Roof his head the what.
但我希望它更短,例如这样的字符串:
kdghdsvvw564645b7573b4657435
我该怎么做?
您可以尝试 smaz 压缩短字符串。您需要连接到 C 代码或重新实现算法。
除了实施或使用压缩算法外,您还需要确保字符对于 URL 是安全的。例如,如果压缩算法压缩为二进制(大多数情况下都是这样做的),那将不适用于 URL。使用一种压缩算法后,需要实现另一种算法,将压缩后的数据转换为url-safe字符串。一些 JavaScript 压缩库,如 lz-string 提供了方便的功能,可以直接压缩或解压缩 URI-safe 文本。
答案取决于您是否要从 URL 字符串中恢复原始文本。
如果要恢复,请先使用无损方法压缩文本,例如建议使用 zlib 库或 smaz 压缩小文本。然后将压缩的二进制输出转换为 URL 安全格式。 Base64 就是这样一种方法。最终字符串可能更短或更长,具体取决于文本的可压缩性。
如果您不想恢复原始文本,只需使用 sha1sum 对您的文本进行哈希处理,然后在您的 URL 字符串中使用它的输出。散列对于两个不同的输入字符串将是唯一的。这是一个例子
~$ cat junk
Put all speaking her delicate recurred possible. Set indulgence inquietude discretion insensible bed why announcing. Middleton fat two satisfied additions. So continued he or commanded household smallness delivered. Door poor on do walk in half. Roof his head the what.
~$ sha1sum junk
e2acae1ae295de73541cd321da268a8d2d48ca7b junk
~$ gzip junk
~$ base64 junk.gz
H4sICFtXTF8AA2p1bmsAHU9LbgMxCN33FO8Ec4puK1XtCYhhYhQPTA3uqLcvyQbB0/vxuRI0BuIU
eqjd0WWCZWijFExpa05hnB6htyEbviWhxmvcxZrU+rNUcrGANdqUVLdCQ+wlwK3UV/8DmfmyVhEb
PpR5SBZxp0RejqDU2LW4xKxPj6goR3NLtVV4F/is+zjI+Hn7Cuk+GHHUAyYRr96/Un03vHuxz+eo
FHZcNB5VC53GvuHLfUfXKFdiZHlfnXJ7+wdZzrQRDgEAAA==
然后,使用 base64 -d 从 URL
中恢复原始文本