对英文文本的字母进行huffman编码,heapq优先队列构建huffman树
python huffman.py source.txt result.txt
 import sys
import heapq
import collections class Node(object):
def __init__(self,value = None,count = 1,left = None,right = None, code = ''):
self.value = value
self.count = count
self.left = left
self.right = right
self.code = code def isleaf(self):
if self.left != None:
return False
elif self.right != None:
return False
else:
return True def __repr__(self):
return "Node(%r,%r)"%(self.value,self.count)
#for sort or priority queue
def __lt__(self,other):
return self.count < other.count
#for operator +
def __add__(self,other):
self.code = 0
other.code = 1
# only leaf node value is need
return Node(self.value+other.value,self.count+other.count,self,other) def getTreeRoot(text):
Counter = collections.Counter(text)
head = [Node(k,v) for (k,v) in Counter.items()]
heapq.heapify(head) while len(head) >= 2:
heapq.heappush(head, heapq.heappop(head) + heapq.heappop(head)) root = head[0]
return root def huffman(root, prefix = []):
code = {}
if root is None:
return code
prefix = prefix + [root.code]
if root.isleaf():
code[root.value] = prefix
else:
code.update(huffman(root.left,prefix))
code.update(huffman(root.right,prefix))
return code def gethuffmantext(text):
root = getTreeRoot(text)
codebook = huffman(root)
for k,v in codebook.items():
newv = "".join(str(char) for char in v)
codebook[k] = newv
print (codebook)
print("The original text size is {}".format(len(text) * 8))
huffmantext = []
lenhuffman = 0
for char in text:
lenhuffman += len(codebook[char])
huffmantext.append(codebook[char])
print ("The huffman code text size is {}".format(lenhuffman)) return huffmantext, codebook, lenhuffman def gettextfromhuffmancode(huffmantext,codebook): reversecodebook = {value:key for (key,value) in codebook.items()} text = []
for huffmancode in huffmantext:
text.append(reversecodebook[huffmancode]) return text if __name__ == "__main__":
text = open(sys.argv[1],"rb").read()
newfile = sys.argv[2]
#huffmantext, codebook, lenhuffman = gethuffmantext("hello world")
huffmantext, codebook, lenhuffman = gethuffmantext(text)
text1 = gettextfromhuffmancode(huffmantext,codebook)
text1 = "".join(str(v) for v in text1) lenoftext = len(text)*8.0
lenofhuffman = lenhuffman print ("The compression ratio is %lf \n" % (1.0 * lenhuffman / lenoftext )) fp = open(newfile,"wb")
fp.write(text1)
fp.close()

huffman编解码英文文本[Python]的更多相关文章

  1. 编解码原理,Python默认解码是ascii

    编解码原理,Python默认解码是ascii 首先我们知道,python里的字符默认是ascii码,英文当然没问题啦,碰到中文的时候立马给跪. 不知道你还记不记得,python里打印中文汉字的时候需要 ...

  2. base64编解码学习及python代码实现

    Base64是一种用64个字符来表示任意二进制数据的方法. Base64编码可以成为密码学的基石.可以将任意的二进制数据进行Base64编码.所有的数据都能被编码为并只用65个字符就能表示的文本文件. ...

  3. Python编解码问题与文本文件处理

    编解码器 在字符与字节之间的转换过程称为编解码,Python自带了超过100种编解码器,比如: ascii(英文体系) gb2312(中文体系) utf-8(全球通用) latin1 utf-16 编 ...

  4. python rsa 加密解密 (编解码,base64编解码)

    最近有需求,需要研究一下RSA加密解密安全:在网上百度了一下例子文章,很少有文章介绍怎么保存.传输.打印加密后的文本信息,都是千篇一律的.直接在一个脚本,加密后的文本信息赋于变量,然后立马调用解密.仔 ...

  5. python base64 编解码,转换成Opencv,PIL.Image图片格式

    二进制打开图片文件,base64编解码,转成Opencv格式: # coding: utf-8 import base64 import numpy as np import cv2 img_file ...

  6. python中的编解码小结

    在用python27写文件或者上传文件时遇到这样一个问题:.在网上搜了下说加入以下三行代码可以解决: import sys reload(sys) sys.setdefaultencoding('ut ...

  7. Huffman树及其编解码

    Huffman树--编解码 介绍:   Huffman树可以根据输入的字符串中某个字符出现的次数来给某个字符设定一个权值,然后可以根据权值的大小给一个给定的字符串编码,或者对一串编码进行解码,可以用于 ...

  8. Python 下JSON的两种编解码方式实例解析

    概念   JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.在日常的工作中,应用范围极其广泛.这里就介绍python下它的两种编解码方法: ...

  9. 【听如子说】-python模块系列-AIS编解码Pyais

    Pyais Module Introduce pyais一个简单实用的ais编解码模块 工作中需要和ais打交道,在摸鱼的过程中发现了一个牛逼的模块,对ais编解码感兴趣的可以拿项目学习一下,或者运用 ...

随机推荐

  1. spring boot 2.0.3+spring cloud (Finchley)1、搭建服务注册和发现组件Eureka 以及构建高可用Eureka Server集群

    一 .搭建Eureka 编写Eureka Server 由于有多个spring boot项目,采用maven多module的结构,项目结构如下: 新建一个maven主工程,在主maven的pom文件中 ...

  2. PHP 日志专题

    PHP堆栈跟踪(php stack trace) PHP message: PHP Stack trace: PHP message: PHP . {main}() PHP message: PHP ...

  3. 动态规划之Fib数列类问题应用

    一,问题描述 有个小孩上楼梯,共有N阶楼梯,小孩一次可以上1阶,2阶或者3阶.走到N阶楼梯,一共有多少种走法? 二,问题分析 DP之自顶向下分析方式: 爬到第N阶楼梯,一共只有三种情况(全划分,加法原 ...

  4. MAC洪水攻击

    MAC洪水攻击原理 传统的交换机在数据转发过程中依靠对CAM表的查询来确定正确的转发接口,一旦在查询过程中无法找到相关的目的MAC对应的条目,此数据帧将作为广播帧来处理,CAM表的容量有限,只能存储不 ...

  5. string中substr,find函数使用

    2.string函数 find:某子串的起始位(0开始),函数的第二个参数使用代表从该位开始的后缀 substr:1) x开始的连续y位 2) x开始的后缀 #include<bits/stdc ...

  6. OBS 录制视频 自己留存

    1. 下载安装 软件下载地址:https://github.com/jp9000/obs-studio/releases/download/19.0.2/OBS-Studio-19.0.2-Full- ...

  7. hadoop - 基础操作

    查看文件: [root@hadoop hadoop]# hadoop fs -lsr /drwxr-xr-x - root supergroup 0 2016-12-27 10:49 /homedrw ...

  8. drozer工具的安装与使用:之二使用篇

    如果英文好的同学可以直接查看官方文档   官方文档连接:https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide ...

  9. SpringMVC参数绑定(四)

    1.默认支持的参数类型 处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值. HttpServletRequest 通过request对象获取请求信息 HttpServletResponse ...

  10. sklearn中的回归器性能评估方法(转)

    explained_variance_score() mean_absolute_error() mean_squared_error() r2_score() 以上四个函数的相同点: 这些函数都有一 ...