9

快速提问。我正在尝试在 Python 中查找或编写一个编码器,以通过使用大小写字母来缩短一串数字。数字字符串看起来像这样:

20120425161608678259146181504021022591461815040210220120425161608667

长度始终相同。

我最初的想法是编写一些简单的编码器来利用大小写字母和数字将这个字符串缩短成看起来更像这样的东西:

a26Dkd38JK

这完全是武断的,只是想尽可能清楚。我确信有一种非常巧妙的方法可以做到这一点,可能已经内置了。也许这是一个令人尴尬的问题,甚至被问到。

此外,我需要能够获取缩短的字符串并将其转换回更长的数值。我应该写一些东西并发布代码,还是这是我应该已经知道的 Python 内置函数?

谢谢!

4

4 回答 4

10

有两个函数是自定义的(不是基于base64),但会产生更短的输出:

chrs = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = len(chrs)

def int_to_cust(i):
    result = ''
    while i:
        result = chrs[i % l] + result
        i = i // l
    if not result:
        result = chrs[0]
    return result

def cust_to_int(s):
    result = 0
    for char in s:
        result = result * l + chrs.find(char)
    return result

结果是:

>>> int_to_cust(20120425161608678259146181504021022591461815040210220120425161608667)
'9F9mFGkji7k6QFRACqLwuonnoj9SqPrs3G3fRx'
>>> cust_to_int('9F9mFGkji7k6QFRACqLwuonnoj9SqPrs3G3fRx')
20120425161608678259146181504021022591461815040210220120425161608667L

如果将其他字符添加到chrs变量中,还可以缩短生成的字符串。

于 2012-04-26T02:04:20.820 回答
10

这是一个很好的压缩:

import base64

def num_to_alpha(num):
    num = hex(num)[2:].rstrip("L")

    if len(num) % 2:
        num = "0" + num

    return base64.b64encode(num.decode('hex'))

它首先将整数转换为字节串,然后 base64 对其进行编码。这是解码器:

def alpha_to_num(alpha):
    num_bytes = base64.b64decode(alpha)
    return int(num_bytes.encode('hex'), 16)

例子:

>>> num_to_alpha(20120425161608678259146181504021022591461815040210220120425161608667)
'vw4LUVm4Ea3fMnoTkHzNOlP6Z7eUAkHNdZjN2w=='
>>> alpha_to_num('vw4LUVm4Ea3fMnoTkHzNOlP6Z7eUAkHNdZjN2w==')
20120425161608678259146181504021022591461815040210220120425161608667
于 2012-04-26T01:38:55.857 回答
1

用“类”来做:

VALID_CHRS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE = len(VALID_CHRS)
MAP_CHRS = {k: v
            for k, v in zip(VALID_CHRS, range(BASE + 1))}


class TinyNum:
    """Compact number representation in alphanumeric characters."""

    def __init__(self, n):
        result = ''
        while n:
            result = VALID_CHRS[n % BASE] + result
            n //= BASE
        if not result:
            result = VALID_CHRS[0]
        self.num = result

    def to_int(self):
        """Return the number as an int."""
        result = 0
        for char in self.num:
            result = result * BASE + MAP_CHRS[char]
        return result

示例用法:

>> n = 4590823745
>> tn = TinyNum(a)
>> print(n)
4590823745
>> print(tn.num)
50GCYh
print(tn.to_int())
4590823745

(基于塔德克的回答。)

于 2019-11-18T15:42:50.460 回答
0
>>> s="20120425161608678259146181504021022591461815040210220120425161608667"
>>> import base64, zlib
>>> base64.b64encode(zlib.compress(s))
'eJxly8ENACAMA7GVclGblv0X4434WrKFVW5CtJl1HyosrZKRf3hL5gLVZA2b'
>>> zlib.decompress(base64.b64decode(_))
'20120425161608678259146181504021022591461815040210220120425161608667'

所以 zlib 在压缩数字字符串方面并不是很聪明:(

于 2012-04-26T01:55:03.963 回答