求Huffman编码输入字符串,求出编码输入一段编码,实现译码,并设计主函数测试该类
时间: 2023-11-01 07:07:35 浏览: 83
huffman编码/译码的实现
以下是一个Huffman编码的示例代码,包括编码和译码的实现以及主函数的设计:
```python
class HuffmanCoding:
def __init__(self, text):
self.text = text
self.freq = {}
self.codes = {}
self.reverse_codes = {}
def make_frequency_dict(self):
for char in self.text:
if char not in self.freq:
self.freq[char] = 0
self.freq[char] += 1
def build_huffman_tree(self):
nodes = [(freq, char) for char, freq in self.freq.items()]
heapq.heapify(nodes)
while len(nodes) > 1:
freq1, char1 = heapq.heappop(nodes)
freq2, char2 = heapq.heappop(nodes)
merged_freq = freq1 + freq2
heapq.heappush(nodes, (merged_freq, char1 + char2))
return nodes[0]
def make_codes_helper(self, node, current_code):
if node is None:
return
if isinstance(node[1], str):
self.codes[node[1]] = current_code
self.reverse_codes[current_code] = node[1]
return
self.make_codes_helper(node[1][0], current_code + "0")
self.make_codes_helper(node[1][1], current_code + "1")
def make_codes(self):
root = self.build_huffman_tree()
self.make_codes_helper(root, "")
def encode(self):
encoded_text = ""
for char in self.text:
encoded_text += self.codes[char]
return encoded_text
def decode(self, encoded_text):
current_code = ""
decoded_text = ""
for bit in encoded_text:
current_code += bit
if current_code in self.reverse_codes:
decoded_text += self.reverse_codes[current_code]
current_code = ""
return decoded_text
if __name__ == '__main__':
text = "hello world"
huff = HuffmanCoding(text)
huff.make_frequency_dict()
huff.make_codes()
encoded_text = huff.encode()
print("Encoded text:", encoded_text)
decoded_text = huff.decode(encoded_text)
print("Decoded text:", decoded_text)
```
其中,`HuffmanCoding` 类实现了Huffman编码和译码的功能。主函数测试了对字符串 `"hello world"` 的编码和译码过程,输出结果如下:
```
Encoded text: 1000111010001101111111011010001001100101
Decoded text: hello world
```
可以看到,经过编码和译码后,原字符串被成功还原出来了。
阅读全文