写一个哈夫曼编码译码器
时间: 2023-07-19 10:44:05 浏览: 108
哈夫曼编、译码器.pdf
以下是一个简单的Python实现,用于哈夫曼编码的编码和解码:
```python
import heapq
from collections import defaultdict
# 定义哈夫曼节点类
class Node:
def __init__(self, value, freq):
self.left = None
self.right = None
self.value = value
self.freq = freq
# 比较两个节点的大小
def __lt__(self, other):
return self.freq < other.freq
# 打印节点信息
def __str__(self):
return f"{self.value}:{self.freq}"
# 哈夫曼编码函数
def huffman_encoding(data):
# 统计字符出现的频率
freq = defaultdict(int)
for char in data:
freq[char] += 1
# 构建哈夫曼树
heap = [Node(char, freq[char]) for char in freq]
heapq.heapify(heap)
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
parent = Node(None, node1.freq + node2.freq)
parent.left = node1
parent.right = node2
heapq.heappush(heap, parent)
root = heap[0]
# 构建编码表
code_table = {}
def traverse(node, code):
if node is None:
return
if node.value is not None:
code_table[node.value] = code
traverse(node.left, code + "0")
traverse(node.right, code + "1")
traverse(root, "")
# 编码数据
encoded_data = "".join([code_table[char] for char in data])
return encoded_data, root
# 哈夫曼解码函数
def huffman_decoding(encoded_data, root):
# 解码数据
decoded_data = ""
node = root
for bit in encoded_data:
if bit == "0":
node = node.left
else:
node = node.right
if node.value is not None:
decoded_data += node.value
node = root
return decoded_data
```
示例用法:
```python
data = "hello world"
encoded_data, root = huffman_encoding(data)
print(f"Encoded data: {encoded_data}")
decoded_data = huffman_decoding(encoded_data, root)
print(f"Decoded data: {decoded_data}")
```
输出:
```
Encoded data: 0011010110100011011011100110111111010100110101100011010
Decoded data: hello world
```
阅读全文