Python:如何将文件转换为自定义基数并返回?

2024-04-24 06:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我想转换成自定义基地(基地86例如,与自定义字母表)

我试图转换文件与hexlify,然后到我的自定义基地,但它太慢了。。。8秒60千欧。。你知道吗

def HexToBase(Hexa, AlphabetList, OccurList, threshold=10):
    number = int(Hexa,16) #base 16 vers base 10
    alphabet = GetAlphabet(AlphabetList, OccurList, threshold)
    #GetAlphabet return a list of all chars that occurs more than threshold times

    b_nbr = len(alphabet) #get the base
    out = ''
    while number > 0:
        out = alphabet[(number % b_nbr)] + out
        number = number // b_nbr
    return out

file = open("File.jpg","rb")
binary_data = file.read()
HexToBase(binascii.hexlify(binary_data),['a','b'],[23,54])

那么,有人能帮我找到正确的解决方案吗?你知道吗

对不起,我英语不好,我是法国人,谢谢你的帮助!你知道吗


Tags: 文件numberbasethresholdreturn基地outnbr
1条回答
网友
1楼 · 发布于 2024-04-24 06:37:22

首先,您可以替换:

int(binascii.hexlify(binary_data), 16) # timeit: 14.349809918712538

签署人:

int.from_bytes(binary_data, byteorder='little') # timeit: 3.3330371951720164

其次,可以使用divmod函数来加速循环:

out = ""
while number > 0:
    number, m = divmod(number, b_nbr)
    out = alphabet[m] + out

# timeit: 3.8345545611298126 vs 7.472579440019706

有关divmod%, //的比较和大数,请参见Is divmod() faster than using the % and // operators?。你知道吗

(备注:我希望buildind一个数组,然后用"".join生成一个字符串会比out = ... + out快,但cpython3.6不是这样的。)

所有这些加起来我的加速系数是6。你知道吗

相关问题 更多 >