2 julie334600 julie334600 于 2016.04.17 15:43 提问

Python中哈夫曼的译码问题

我通过编码,对一个含有一大段字符串的文本得到了一个dict和一段编码完成的01字符串,dict中Keys为字符,value为权,不用树,怎么直接根据dict和01字符串译码回去?
比如 00100110101011011100111010101100111011101111010011110011101010110001000100110110101011001111001111110000000111111000001100000010100111111011110011101010111010101

dict:
a:110
C:00100
e:11110
d:01
g:11111
f:0000
h:00101
c:00110
q:1001
s:101
r:00111
w:1110
y:10000
x:0001
z:10001

求解

1个回答

bealing
bealing   Rxr 2016.04.17 17:11

仅供参考

 #coding:utf-8
'''
Created on 2016/4/17
@author: Bealing
'''

data = '00100110101011011100111010101100111011101111010011110011101010110001000100110110101011001111001111110000000111111000001100000010100111111011110011101010111010101'
code = {'a':'110','C':'00100','e':'11110','d':'01','g':'11111','f':'0000','h':'00101','c':'00110','q':'1001','s':'101','r':'00111','w':'1110','y':'10000','x':'0001','z':'10001'}

def haffuman_decode(data,code):
    newcode = dict(zip(code.values(), code.keys())) #字典key/value翻转
    i,res = 0,""
    while i < len(data):
        j = i+1
        while j < len(data): #获取某一字符的code
            if data[i:j] in newcode.keys():
                break
            j += 1
        res += newcode.get(data[i:j]) #获取某一code表示的字符,并追加在字符串后面
        i = j
    return res

if __name__ == '__main__':
    print haffuman_decode(data, code)
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!