给我做一个python 用哈夫曼编码来压缩文字或文件的代码
时间: 2024-09-21 20:04:18 浏览: 30
Huffman 编码图像无损压缩和解压缩 Python示例代码 哈夫曼编码
5星 · 资源好评率100%
当然可以。Huffman 编码是一种用于数据压缩的无损压缩算法,它基于构建哈夫曼树的过程。以下是使用 Python 实现哈夫曼编码的一个简单示例,我们将创建一个类来生成和应用编码:
```python
from collections import Counter
import heapq
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(freqs):
heap = [Node(char, freq) for char, freq in freqs.items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = Node(None, left.freq + right.freq)
merged.left = left
merged.right = right
heapq.heappush(heap, merged)
return heap[0]
def create_encoding(root):
encoding = {}
def traverse(node, code=""):
if node.char is not None:
encoding[node.char] = code
else:
traverse(node.left, code + "0")
traverse(node.right, code + "1")
traverse(root)
return encoding
# 示例文本
text = "hello world"
freqs = Counter(text)
root = build_huffman_tree(freqs)
encoding = create_encoding(root)
compressed_text = "".join(encoding[char] for char in text)
decompressed_text = "".join(encoding[char] for char in compressed_text)
print(f"原始文本: {text}")
print(f"压缩后的文本: {compressed_text}")
print(f"解压后的文本: {decompressed_text}")
阅读全文