【知识发现】python开源哈夫曼编码库huffman

本文介绍如何使用Python的huffman库构建哈夫曼树并进行编码,提供了实际案例和构建哈夫曼树的详细步骤。适用于压缩算法的学习与实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、哈夫曼树:


   安装:pip install huffman


   Github地址: https://github.com/nicktimko/huffman
   pypi地址:https://pypi.python.org/pypi/huffman
   源码很值得参考。


2、案例:

# -*- coding: utf-8 -*-
'''
Created on 2017年9月26日

@author: Administrator
'''
import huffman
import collections

t1=huffman.codebook([('A', 2), ('B', 4), ('C', 1), ('D', 1)])
print (t1)
t2=huffman.codebook(collections.Counter('man the stand banana man').items())
print (t2)

说明:rovided an iterable of 2-tuples in (symbol, weight) format, generate a Huffman codebook, returned as a dictionary in {symbol: code, ...} format.

3、构造哈夫曼树参考:

#构造哈夫曼树
import heapq
trees=huff_df.values.T.tolist()  #dataframe转化成list
heapq.heapify(trees)
while len(trees)>1:
    rightChild,leftChild=heapq.heappop(trees),heapq.heappop(trees)
    parentNode=(leftChild[0]+rightChild[0],leftChild,rightChild)
    heapq.heappush(trees,parentNode)
print (trees)

huff_df是一个dataframe,转化成list,里面是结点及其频率。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值