利用python生成定义哈夫曼树及哈夫曼编码的代码
时间: 2023-07-19 08:24:10 浏览: 124
以下是用Python实现哈夫曼树和哈夫曼编码的代码:
```python
from heapq import heappush, heappop, heapify
from collections import defaultdict
def huffman_encoding(nodes):
if len(nodes) == 1:
return {nodes[0][0]: '0'}
heap = [[freq, [symbol, '']] for symbol, freq in nodes]
heapify(heap)
while len(heap) > 1:
lo = heappop(heap)
hi = heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return dict(sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)))
def huffman_decoding(encoded_text, code_dict):
current_code = ''
decoded_text = ''
for char in encoded_text:
current_code += char
if current_code in code_dict:
decoded_text += code_dict[current_code]
current_code = ''
return decoded_text
def create_huffman_tree(text):
freq_dict = defaultdict(int)
for char in text:
freq_dict[char] += 1
nodes = list(freq_dict.items())
code_dict = huffman_encoding(nodes)
return code_dict
```
这个代码中,`huffman_encoding` 函数用于生成哈夫曼编码,`huffman_decoding` 函数用于解码哈夫曼编码,`create_huffman_tree` 函数用于生成哈夫曼树。
你可以使用 `create_huffman_tree` 函数来生成哈夫曼树,然后再使用 `huffman_encoding` 函数生成哈夫曼编码。例如:
```python
text = 'hello world'
code_dict = create_huffman_tree(text)
encoded_text = ''.join([code_dict[char] for char in text])
decoded_text = huffman_decoding(encoded_text, code_dict)
print('Original text:', text)
print('Encoded text:', encoded_text)
print('Decoded text:', decoded_text)
```
输出结果为:
```
Original text: hello world
Encoded text: 1011110111010001111101110011000110111100
Decoded text: hello world
```
阅读全文