压缩算法有很多种,这里我将为您提供一个简单的哈夫曼编码(Huffman Coding)算法的Python源码,哈夫曼编码是一种广泛使用的无损数据压缩算法。
import heapq from collections import defaultdict def huffman_encoding(data): if not data: return "", None # 计算每个字符的频率 frequency = defaultdict(int) for char in data: frequency[char] += 1 # 使用优先队列构建哈夫曼树 heap = [[weight, [char, ""]] for char, weight in frequency.items()] heapq.heapify(heap) while len(heap) > 1: lo = heapq.heappop(heap) hi = heapq.heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) # 生成哈夫曼编码表 huff_codes = {} for pair in heap[0][1:]: char, code = pair huff_codes[char] = code # 编码输入数据 encoded_data = "".join(huff_codes[char] for char in data) return encoded_data, huff_codes def huffman_decoding(encoded_data, huff_codes): if not encoded_data or not huff_codes: return "" # 反转哈夫曼编码表,以便解码 reversed_codes = {code: char for char, code in huff_codes.items()} decoded_data = [] current_code = "" for bit in encoded_data: current_code += bit if current_code in reversed_codes: decoded_data.append(reversed_codes[current_code]) current_code = "" return "".join(decoded_data) if __name__ == "__main__": data = "this is an example for huffman encoding" encoded_data, huff_codes = huffman_encoding(data) print("Encoded data:", encoded_data) print("Huffman codes:", huff_codes) decoded_data = huffman_decoding(encoded_data, huff_codes) print("Decoded data:", decoded_data)
这个代码实现了哈夫曼编码和解码的功能,它计算输入数据中每个字符的频率,然后使用优先队列构建哈夫曼树,它生成哈夫曼编码表,并将输入数据编码为二进制字符串,它使用哈夫曼编码表将编码后的数据解码回原始数据。
以上内容就是解答有关压缩算法源码的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1115107.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复