python实现Huffman编码

一、问题

利用二叉树的结构对Huffman树进行编码,实现最短编码

二、解决

  1 # 构建节点类
  2 class TreeNode:
  3     def __init__(self, data):
  4         """
  5         :data is a tuple the first element is value and the second is priority
  6         :param data:
  7         """
  8         self.value = data[0]
  9         self.priority = data[1]
 10         self.left_child = None
 11         self.right_child = None
 12         self.code = ""
 13 
 14 
 15 # 创建树节点队列的函数
 16 def create_node_queue(codes):
 17     queue = []
 18     for code in codes:
 19         queue.append(TreeNode(code))
 20     return queue
 21 
 22 
 23 # 在队列中间添加新的节点元素并保证优先度从大到小排列
 24 def add_queue(queue, node_new):
 25     if len(queue) == 0:
 26         return [node_new]
 27     for i in range(len(queue)):
 28         if queue[i].priority >= node_new.priority:
 29             return queue[:i] + [node_new] + queue[i:]
 30     return queue + [node_new]
 31 
 32 
 33 # 节点队列类
 34 class NodeQueue:
 35     def __init__(self, code):
 36         self.queue = create_node_queue(code)
 37         self.size = len(self.queue)
 38 
 39     def add_node(self, node):
 40         self.queue = add_queue(self.queue, node)
 41         self.size += 1
 42 
 43     def pop_node(self):
 44         self.size -= 1
 45         return self.queue.pop(0)
 46 
 47 
 48 # 各个字符在字符串中出现的次数 即计算优先度
 49 def frequent_char(string_s):
 50     store_d = {}
 51     for c in string_s:
 52         if c not in store_d:
 53             store_d[c] = 1
 54         else:
 55             store_d[c] += 1
 56     return sorted(store_d.items(), key=lambda x: x[1])
 57 
 58 
 59 # 创建Huffman树
 60 def create_huffman_tree(node_queue):
 61     while node_queue.size != 1:
 62         node1 = node_queue.pop_node()
 63         node2 = node_queue.pop_node()
 64         r_1 = TreeNode([None, node1.priority + node2.priority])
 65         r_1.left_child = node1
 66         r_1.right_child = node2
 67         node_queue.add_node(r_1)
 68     return node_queue.pop_node()
 69 
 70 
 71 code_dict1 = {}
 72 code_dict2 = {}
 73 
 74 
 75 # 由Huffman树得到的Huffman编码表
 76 def huffman_code_dict(head, x):
 77     # global code_dict, code_list
 78     if head:
 79         huffman_code_dict(head.left_child, x + "0")
 80         head.code += x
 81         if head.value:
 82             code_dict2[head.code] = head.value
 83             code_dict1[head.value] = head.code
 84         huffman_code_dict(head.right_child, x + "1")
 85 
 86 
 87 # 字符串编码
 88 def trans_encode(string_s):
 89     # global code_dict1
 90     trans_code = ""
 91     for c in string_s:
 92         trans_code += code_dict1[c]
 93     return trans_code
 94 
 95 
 96 # 字符串解码
 97 def trans_decode(string_s):
 98     # global code_dict1
 99     code = ""
100     answer = ""
101     for c in string_s:
102         code += c
103         if code in code_dict2:
104             answer += code_dict2[code]
105             code = ""
106     return answer

 

三、总结
利用Huffman树的编码形式可以进行数据的压缩,因此Huffman的应用也很广泛。在此记录一下方便以后查看。

转载于:https://www.cnblogs.com/future-dream/p/10801934.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于PythonHuffman编码实现: ```python import heapq from collections import defaultdict def huffman_encoding(data): # 构建字符频率字典 freq_dict = defaultdict(int) for char in data: freq_dict[char] += 1 # 将字符频率字典转换为堆 heap = [[freq, [char, ""]] for char, freq in freq_dict.items()] heapq.heapify(heap) # 合并堆中的节点,构建Huffman树 while len(heap) > 1: left = heapq.heappop(heap) right = heapq.heappop(heap) for pair in left[1:]: pair[1] = '0' + pair[1] for pair in right[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [left[0] + right[0]] + left[1:] + right[1:]) # 构建编码字典 encoding_dict = dict(heapq.heappop(heap)[1:]) # 返回编码后的数据和编码字典 encoded_data = "" for char in data: encoded_data += encoding_dict[char] return encoded_data, encoding_dict def huffman_decoding(encoded_data, encoding_dict): # 构建反向编码字典 decoding_dict = {v: k for k, v in encoding_dict.items()} # 解码数据 current_code = "" decoded_data = "" for bit in encoded_data: current_code += bit if current_code in decoding_dict: decoded_data += decoding_dict[current_code] current_code = "" return decoded_data ``` 示例用法: ```python data = "hello world" encoded_data, encoding_dict = huffman_encoding(data) decoded_data = huffman_decoding(encoded_data, encoding_dict) print("Encoded data:", encoded_data) print("Decoded data:", decoded_data) ``` 输出: ``` Encoded data: 0110110111000110010011110100111100001010101101101110001 Decoded data: hello world ``` 这个实现使用了Python的heapq和collections模块,用于构建堆和默认字典。它首先构建字符频率字典,然后将其转换为堆。接下来,它在堆中合并节点,直到只剩下一个节点为止。合并过程中,左分支被标记为0,右分支被标记为1。最终,编码字典被构建,用于编码数据。解码过程中,使用反向编码字典将编码数据转换为原始数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值