3、用Huffman编码方法,实现对任意通信字符的编码和解码。(输入任意字符串)
时间: 2024-05-03 16:17:35 浏览: 129
首先,我们需要统计输入字符串中每个字符出现的频率。然后,根据频率构建Huffman树,并生成每个字符的Huffman编码。最后,将输入字符串用生成的Huffman编码进行编码,或者将编码后的二进制数据进行解码还原成原始字符串。
以下是Python实现代码:
```python
from queue import PriorityQueue
# 定义Huffman树节点类
class Node:
def __init__(self, freq, symbol, left=None, right=None):
self.freq = freq # 频率
self.symbol = symbol # 字符
self.left = left # 左子节点
self.right = right # 右子节点
def __lt__(self, other):
return self.freq < other.freq # 按照频率比较大小
# 统计字符频率
def count_freq(text):
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
return freq
# 构建Huffman树
def build_huffman_tree(freq):
pq = PriorityQueue()
for ch in freq:
pq.put(Node(freq[ch], ch))
while pq.qsize() > 1:
left = pq.get()
right = pq.get()
parent = Node(left.freq+right.freq, None, left, right)
pq.put(parent)
return pq.get()
# 生成Huffman编码
def generate_huffman_code(node, current_code, huffman_code):
if node is None:
return
if node.symbol is not None:
huffman_code[node.symbol] = current_code
return
generate_huffman_code(node.left, current_code+'0', huffman_code)
generate_huffman_code(node.right, current_code+'1', huffman_code)
# 编码
def encode(text, huffman_code):
encoded_text = ''
for ch in text:
encoded_text += huffman_code[ch]
return encoded_text
# 解码
def decode(encoded_text, node):
decoded_text = ''
current_node = node
for bit in encoded_text:
if bit == '0':
current_node = current_node.left
else:
current_node = current_node.right
if current_node.symbol is not None:
decoded_text += current_node.symbol
current_node = node
return decoded_text
# 测试
text = input("请输入要编码的字符串:")
freq = count_freq(text)
huffman_tree = build_huffman_tree(freq)
huffman_code = {}
generate_huffman_code(huffman_tree, '', huffman_code)
encoded_text = encode(text, huffman_code)
decoded_text = decode(encoded_text, huffman_tree)
print("原始字符串:", text)
print("编码后的字符串:", encoded_text)
print("解码后的字符串:", decoded_text)
```
例如,输入字符串为"hello world",则输出结果为:
```
请输入要编码的字符串:hello world
原始字符串: hello world
编码后的字符串: 01010110111001100011000111101110100001101011101011010110010
解码后的字符串: hello world
```
阅读全文