帮我写一段代码 输入一串字符串,根据给定的字符串中字符出现的频率建立相应哈夫曼树,构造哈夫曼编码表,在此基础上可以对待压缩文件进行压缩(即编码),同时可以对压缩后的二进制编码文件进行解压(即译码)。
时间: 2024-05-01 17:17:44 浏览: 69
【C++】根据输入的字符串生成哈夫曼树, 并进行哈夫曼编码和解码
5星 · 资源好评率100%
好的,以下是参考代码:
```
import heapq
from collections import Counter, namedtuple
class HuffmanNode(namedtuple("HuffmanNode", ["left", "right"])):
def walk(self, code, acc):
self.left.walk(code, acc + "0")
self.right.walk(code, acc + "1")
class HuffmanLeaf(namedtuple("HuffmanLeaf", ["char"])):
def walk(self, code, acc):
code[self.char] = acc or "0"
def huffman_encode(s):
heap = []
for char, freq in Counter(s).items():
heap.append((freq, len(heap), HuffmanLeaf(char)))
heapq.heapify(heap)
count = len(heap)
while len(heap) > 1:
freq1, _count1, left = heapq.heappop(heap)
freq2, _count2, right = heapq.heappop(heap)
heapq.heappush(heap, (freq1 + freq2, count, HuffmanNode(left, right)))
count += 1
code = {}
if heap:
[(_freq, _count, root)] = heap
root.walk(code, "")
return code
def huffman_compress(s, code):
return "".join(code[char] for char in s)
def huffman_decompress(c, code):
inv_code = {v: k for k, v in code.items()}
chars = []
bitstring = ""
for bit in c:
bitstring += bit
if bitstring in inv_code:
chars.append(inv_code[bitstring])
bitstring = ""
return "".join(chars)
# 测试
original = "this is a test string"
code = huffman_encode(original)
compressed = huffman_compress(original, code)
print(compressed)
decompressed = huffman_decompress(compressed, code)
print(decompressed)
assert original == decompressed
```
阅读全文