iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python语言实现哈夫曼编码
  • 846
分享到

Python语言实现哈夫曼编码

语言Python哈夫曼 2023-01-31 06:01:32 846人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

汉语版:使用python实现huffman编码是一个能够很快地实现。所以我们选择使用Python来实现我们这个程序。 l E-version: we will use python to realize this program call

汉语版:使用python实现huffman编码是一个能够很快地实现。所以我们选择使用Python来实现我们这个程序。 l

E-version: we will use python to realize this program called huffman encoding and decoding. why we use python, because in python we can finish this program faster then other codes. this program are not the final implementation. actually, this is the first version i commit to git. i changed a lot in the least version . so if you run those codes on your environment. some problems may be exist; don`t worry, the first four drafts are right, you  can build everything based on them. so Good lucky to you.

I:实现节点类

class node:
    def __init__(self,freq):
        self.left = None
        self.right = None
        self.father = None
        self.freq = freq

    def is_left(self):
        return self.father.left == self

II:为每一个节点赋权值

def create_nodes(frequencies):
    return [Node(freq) for freq in frequencies]

III:创建哈夫曼树

def create_huffman_tree(nodes):
    queue = nodes[:]
    while len(queue) > 1:
        queue.sort(key=lambda item: item.freq)
        node_left = queue.pop(0)
        node_right = queue.pop(0)
        node_father = Node(node_left.freq + node_right.freq)
        node_father.left = node_left
        node_father.right = node_right
        node_left.father = node_father
        node_right.father = node_father
        queue.append(node_father)
    queue[0].father = None
    return queue[0]

III:遍历叶节点

def huffman_encoding(nodes, root):
    codes = [''] * len(nodes)
    for i in range(len(nodes)):
        node_tmp = nodes[i]
        while node_tmp != root:
            if node_tmp.is_left():
                codes[i] = '0' + codes[i]
            else:
                codes[i] = '1' + codes[i]
            node_tmp = node_tmp.father
    return codes

IV:获取字符出现的频数

# 获取字符出现的频数
def count_frequency(input_string):
    # 用于存放字符
    char_store = []
    # 用于存放频数
    freq_store = []

    # 解析字符串
    for index in range(len(input_string)):
        if char_store.count(input_string[index]) > 0:
            temp = int(freq_store[char_store.index(input_string[index])])
            temp = temp + 1
            freq_store[char_store.index(input_string[index])] = temp
        else:
            char_store.append(input_string[index])
            freq_store.append(1)
    # 返回字符列表和频数列表
    return char_store, freq_store

V:获取字符、频数的列表

# 获取字符、频数的列表
def get_char_frequency(char_store=[], freq_store=[]):
    # 用于存放char_frequency
    char_frequency = []
    for item in zip(char_store, freq_store):
        temp = (item[0], item[1])
        char_frequency.append(temp)
    return char_frequency

VI:将字符转换成哈夫曼编码


# 将字符转换成huffman编码
def get_huffman_file(input_string, char_frequency, codes):
    # 逐个字符替换
    file_content = ''
    for index in range(len(input_string)):
        for item in zip(char_frequency, codes):
            if input_string[index] == item[0][0]:
                file_content = file_content + item[1]
    file_name = 'huffman_' + str(uuid.uuid1())+'.txt'
    with open(file_name, 'w+') as destination:
        destination.write(file_content)
    return file_name

VII:解压缩哈夫曼文件

# 解压缩huffman文件
def decode_huffman(input_string,  char_store, freq_store):
    encode = ''
    decode = ''
    for index in range(len(input_string)):
        encode = encode + input_string[index]
        for item in zip(char_store, freq_store):
            if encode == item[1]:
                decode = decode + item[0]
                encode = ''
    return decode

VIII:计算压缩比(写错了,可以自行改写)

# 计算压缩比
def get_encode_ration(codes):
    # 计算所需要的二进制个数
    h_length = 0
    for item in codes:
        h_length = h_length + len(item)
    t_length = bin_middle(len(codes))*len(codes)
    ratio = t_length/h_length
    return str(ratio)[0:3]

# 计算所在的二进制空间
def bin_middle(number):
    n, i = 1, 0
    while n < number:
        n = n * 2
        i = i + 1
    return i

最后:Django文件接收,并返回


def upload(request):
    ctx = {}
    if request.method == "POST":
        file_name = str(request.FILES['file'])
        if not file_name.endswith('txt'):
            ctx['fail'] = 'file fORMat exist wrong!'
        else:
            file = request.FILES['file']
            ctx['success'] = 'Successful'
            input_string = tool.read_file(tool.save_file(file))
            char_store, freq_store = tool.count_frequency(input_string)
            char_frequency = tool.get_char_frequency(char_store, freq_store)
            nodes = huf.create_nodes([item[1] for item in char_frequency])
            root = huf.create_huffman_tree(nodes)
            codes = huf.huffman_encoding(nodes, root)
            save_file_name = tool.get_huffman_file(input_string, char_frequency, codes)
            for item in zip(char_frequency, codes):
                print('Character:%s freq:%-2d   encoding: %s', item[0][0], item[0][1], item[1])
            ctx['node'] = char_frequency

            def file_iterator(files, chunk_size=512):
                with open(files) as f:
                    while True:
                        c = f.read(chunk_size)
                        if c:
                            yield c
                        else:
                            break
            the_file_name = tool.get_encode_ration(codes)+'_'+str(uuid.uuid1())+'.txt'
            response = StreamingHttpResponse(file_iterator(save_file_name))
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
            return response


--结束END--

本文标题: Python语言实现哈夫曼编码

本文链接: https://www.lsjlt.com/news/190233.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python语言实现哈夫曼编码
    汉语版:使用python实现huffman编码是一个能够很快地实现。所以我们选择使用python来实现我们这个程序。 l E-version: we will use python to realize this program call...
    99+
    2023-01-31
    语言 Python 哈夫曼
  • 利用Python和C语言分别实现哈夫曼编码
    目录1.C语言实现1.1代码说明1.2运行结果2.Python实现2.1代码说明2.2运行结果1.C语言实现 1.1代码说明 a  创建双向链表: 在创建哈夫曼树的过程中,...
    99+
    2022-11-11
  • C语言实现BMP图像处理(哈夫曼编码)
    哈夫曼(Huffman)编码是一种常用的压缩编码方法,是 Huffman 于 1952 年为压缩文本文件建立的。它的基本原理是频繁使用的数据用较短的代码代替,较少使用的数据用较长的代...
    99+
    2022-11-12
  • 如何利用Python和C语言分别实现哈夫曼编码
    1.C语言实现1.1代码说明a 创建双向链表:在创建哈夫曼树的过程中,需要不断对结点进行更改和删除,所以选用双向链表的结构更容易'''C #include <stdlib.h> #include <...
    99+
    2023-05-22
    Python C语言
  • 哈夫曼树实现 python
    参考博客: http://linux.xidian.edu.cn/bbs/thread-70-1-1.html 基本上相当于抄写一遍了。。呃呃。。。...
    99+
    2023-01-31
    哈夫曼树 python
  • C语言实现哈夫曼树的方法
    本文实例为大家分享了C语言实现哈夫曼树的具体代码,供大家参考,具体内容如下 准备工作: 1、定义一个结构体,表示一个节点。其中,这个结构体有4个成员变量,分别表示是这个节点的权值,父...
    99+
    2022-11-12
  • Java利用哈夫曼编码实现字符串压缩
    赫夫曼编码基本介绍 1) 赫夫曼编码也翻译为 哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式, 属于一种程序算法 2) 赫夫曼编码是赫哈夫曼树在电讯通信中...
    99+
    2022-11-13
  • 用R语言实现霍夫曼编码的示例代码
    可读性极低,而且其实也没必要用R语言写,图个乐罢了  p=c(0.4,0.2,0.2,0.1,0.1)###输入形如c(0.4,0.2,0.2,0.1,0.1)的概率向...
    99+
    2022-11-11
  • 怎么利用java语言实现一个哈夫曼压缩功能
    本篇文章给大家分享的是有关怎么利用java语言实现一个哈夫曼压缩功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。哈夫曼压缩的原理: 通过统计文件中每个字节出现的频率,将8位的...
    99+
    2023-05-31
    java 哈夫曼压缩 ava
  • 基于C语言利用哈夫曼树实现文件压缩的问题
    一、哈夫曼树         具有n个权值的n个叶子结点,构造出一个二叉树,使得该树的带权路径长度(W...
    99+
    2022-11-12
  • 使用R语言怎么编写一个霍夫曼编码
    本篇文章给大家分享的是有关使用R语言怎么编写一个霍夫曼编码,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。p=c(0.4,0.2,0.2,0.1,0.1)###输入形如c(0.4...
    99+
    2023-06-14
  • js如何实现哈弗曼编码
    小编给大家分享一下js如何实现哈弗曼编码,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!需要的朋友可以参考下哈夫曼编码,根据每个单...
    99+
    2022-10-19
  • Python用户推荐系统曼哈顿算法实现完整代码
    出租车几何或曼哈顿距离(Manhattan Distance)是由十九世纪的赫尔曼·闵可夫斯基所创词汇 ,是种使用在几何度量空间的几何学用语,用以标明两个点在标准坐标系上的绝对轴距总和。 图中红线代表曼哈...
    99+
    2022-06-04
    曼哈顿 算法 完整
  • Go语言实现Base64、Base58编码与解码
    目录1. 常见的编码2. go语言实现base64的编码与解码2.1 Base64编码原理2.2 实现Base64的编码与解码3. go语言实现base58编码与解码3.1 base...
    99+
    2022-11-12
  • 怎么用Java语言实现Base64编码
    小编给大家分享一下怎么用Java语言实现Base64编码,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!import java.io.*; public class MIMEBase64 { static String B...
    99+
    2023-06-03
  • c语言中怎么实现qp编解码
    本篇文章给大家分享的是有关c语言中怎么实现qp编解码,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。 void DecodeQP(ngx_str_t *des...
    99+
    2023-06-04
  • Java语言编码规范中如何实现布局
    小编给大家分享一下Java语言编码规范中如何实现布局,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!Java语言编码规范3 布局(Placement)只在代码块的开...
    99+
    2023-06-03
  • HTTP 函数同步编写指南:Python 语言实现
    HTTP 函数是一个在云环境下部署的函数,它可以被调用来处理 HTTP 请求。这种函数非常适合处理 Web 应用程序和 RESTful API,因为它们可以快速响应客户端请求。本文将介绍如何使用 Python 语言实现 HTTP 函数,并...
    99+
    2023-09-21
    http 函数 同步
  • 汇编语言怎么实现各种码制的转换
    本篇内容主要讲解“汇编语言怎么实现各种码制的转换”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“汇编语言怎么实现各种码制的转换”吧!1.十六进制转换为二进制数设计1.1设计要求:设计转换程序,将键...
    99+
    2023-06-21
  • Python编程语言的实现内幕是怎么样的
    这篇文章将为大家详细讲解有关Python编程语言的实现内幕是怎么样的,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。Python“ 时,他们可能想到的是有时称为 ”CPython“(因为它是以...
    99+
    2023-06-17
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作