对英文文本的字母进行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. cdqz2017-test8-Tree(点分树)

    n个点的带点权带边权的树,设点权为a[i],边权为b[i] 一棵树有n*(n-1)/2个点对, 定义这棵树的价值为任意两点对的(a[x]^a[y])*dis(x,y) 有m次修改一个点的点权的操作 输 ...

  2. 使用Spring时web.xml中的配置

    使用Spring时web.xml中的配置: <?xml version="1.0" encoding="UTF-8"?> <web-app x ...

  3. Shell结合Expect实现自动输入密码

    Shell结合Expect自动输入密码示例 #!/bin/bash cd /data/live /usr/bin/expect <<-EOF spawn git clone "s ...

  4. 用ajax传递json,返回前台的中文乱码问题

    java项目中用ajax传递json,返回前台时中文出现问号(乱码问题)的解决办法 首先看一下没有解决前的状态: 我用的框架是ssm,在springMVC中我配置了编码格式为utf-8,每个jsp页面 ...

  5. Elastic Job入门(2) - 使用

    运维平台 elastic-job-lite-console-${version}.tar.gz可通过mvn install编译获取,下载源码,进入console目录,执行: mvn clean ins ...

  6. luogu P3243 [HNOI2015]菜肴制作

    这题一看就知道和拓扑序有关 考虑拓扑排序的时候每次取队列里最小的数进行排序 然后就\(\mathcal{GG}\)了,因为这样只能使字典序最小,而并不能保证题目中要求的每个编号的数要在满足前面数尽量在 ...

  7. TypeError: view must be a callable or a list/tuple in the case of include()

    原文连接: http://www.imooc.com/qadetail/98920 我是这么写的就好了 from django.conf.urls import url from django.con ...

  8. F - Set of Strings

    You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concat ...

  9. 2017-2018-2 165X 『Java程序设计』课程 助教总结

    2017-2018-2 165X 『Java程序设计』课程 助教总结 本学期完成的助教工作主要包括: 编写300道左右测试题,用于蓝墨云课下测试: 发布博客三篇:<2017-2018-2 165 ...

  10. 如何将SVN仓库转换为Git仓库

    按如下步骤操作就可以将SVN仓库完整的转换为Git仓库: 1) 将远程SVN仓库搬到本地(这一步主要是为了提高转换的速度,也可以忽略)     参考这篇文章: http://rongjih.blog. ...