julie334600
julie334600
采纳率0%
2016-04-17 07:43 阅读 2.0k

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 xSeeker~ 2016-04-17 09: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)
    
    点赞 评论 复制链接分享

相关推荐