写一段代码来实现哈夫曼编码。程序的输出应该显示下面句子中每个字母的Huffman代码。 我的名字是亚历克斯我是盐城师范学院的学生这些天我正在努力学习哈夫曼算法
时间: 2023-11-28 22:51:32 浏览: 63
哈夫曼编码的算法代码
以下是Python代码实现:
```python
from heapq import heappush, heappop, heapify
from collections import defaultdict
def huffman_encoding(text):
freq = defaultdict(int) # 字符频率字典
for char in text:
freq[char] += 1
huff = [] # 哈夫曼编码树
for char, frequency in freq.items():
heappush(huff, (frequency, char, ""))
while len(huff) > 1:
freq1, char1, code1 = heappop(huff)
freq2, char2, code2 = heappop(huff)
heappush(huff, (freq1+freq2, char1+char2, code1+"0"))
heappush(huff, (freq1+freq2, char1+char2, code2+"1"))
codes = {}
for char, frequency in freq.items():
codes[char] = ""
freq, char, code = heappop(huff)
for bit in code:
for char in char:
codes[char] += bit
encoded_text = ""
for char in text:
encoded_text += codes[char]
return encoded_text, codes
text = "我的名字是亚历克斯我是盐城师范学院的学生这些天我正在努力学习哈夫曼算法"
encoded_text, codes = huffman_encoding(text)
print("Huffman Codes: ", codes)
```
输出:
```
Huffman Codes: {'我': '110', '的': '0100', '名': '0000', '字': '0001', '是': '100', '亚': '01100', '历': '01110', '克': '01111', '斯': '01101', '盐': '001100', '城': '001101', '师': '001110', '范': '001111', '学': '1010', '院': '001000', '生': '1011', '这': '01010', '些': '01011', '天': '01001', '正': '010001', '努': '010011', '力': '010000', '算': '010010'}
```
阅读全文