huffman编解码英文文本[Python]
对英文文本的字母进行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]的更多相关文章
- 编解码原理,Python默认解码是ascii
编解码原理,Python默认解码是ascii 首先我们知道,python里的字符默认是ascii码,英文当然没问题啦,碰到中文的时候立马给跪. 不知道你还记不记得,python里打印中文汉字的时候需要 ...
- base64编解码学习及python代码实现
Base64是一种用64个字符来表示任意二进制数据的方法. Base64编码可以成为密码学的基石.可以将任意的二进制数据进行Base64编码.所有的数据都能被编码为并只用65个字符就能表示的文本文件. ...
- Python编解码问题与文本文件处理
编解码器 在字符与字节之间的转换过程称为编解码,Python自带了超过100种编解码器,比如: ascii(英文体系) gb2312(中文体系) utf-8(全球通用) latin1 utf-16 编 ...
- python rsa 加密解密 (编解码,base64编解码)
最近有需求,需要研究一下RSA加密解密安全:在网上百度了一下例子文章,很少有文章介绍怎么保存.传输.打印加密后的文本信息,都是千篇一律的.直接在一个脚本,加密后的文本信息赋于变量,然后立马调用解密.仔 ...
- python base64 编解码,转换成Opencv,PIL.Image图片格式
二进制打开图片文件,base64编解码,转成Opencv格式: # coding: utf-8 import base64 import numpy as np import cv2 img_file ...
- python中的编解码小结
在用python27写文件或者上传文件时遇到这样一个问题:.在网上搜了下说加入以下三行代码可以解决: import sys reload(sys) sys.setdefaultencoding('ut ...
- Huffman树及其编解码
Huffman树--编解码 介绍: Huffman树可以根据输入的字符串中某个字符出现的次数来给某个字符设定一个权值,然后可以根据权值的大小给一个给定的字符串编码,或者对一串编码进行解码,可以用于 ...
- Python 下JSON的两种编解码方式实例解析
概念 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.在日常的工作中,应用范围极其广泛.这里就介绍python下它的两种编解码方法: ...
- 【听如子说】-python模块系列-AIS编解码Pyais
Pyais Module Introduce pyais一个简单实用的ais编解码模块 工作中需要和ais打交道,在摸鱼的过程中发现了一个牛逼的模块,对ais编解码感兴趣的可以拿项目学习一下,或者运用 ...
随机推荐
- 匿名内部类中使用的外部局部变量为什么只能是final变量
被匿名内部类引用的变量会被拷贝一份到内部类的环境中 但其后,在外部,该变量如果被修改,则内部外部不一致 Java为了避免数据不同步的问题,做出了匿名内部类只可以访问final的局部变量的限制. 究其原 ...
- Jupyter 魔术命令(magic commands)
自动重新加载更改的模块 命令参数如下所示: %autoreload: 自动重载%aimport排除的模块之外的所有模块. %autoreload 0: 禁用自动重载 %autoreload 1: 自动 ...
- 微信接口开发之高级篇系列【微信权限封装类WechatAuth】
ThinkPHP框架目录结构: <?php /** * Created by PhpStorm. * User: Tinywan * Date: 2016/9/11 * Time: 9:55 * ...
- C语言实现二叉树的建立、遍历以及表达式的计算
实现代码 #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <ctype ...
- dp填表法,刷表法
填表法:利用上一状态推当前 刷表法:利用当前推关联,利用刷表法较为便捷,向上边界较容易处理,处理在本次循环中的影响
- luogu P1762 偶数
打表找规律吼题哇 首先打出\(1-1000\)内的答案的表 0 0 1 1 4 6 9 9 16 ... 448363 ~~有个**规律啊qwq~~ 然后想到用\(\frac{n(n+1)}{2}\) ...
- MySQL备份可能遇到的坑
MySQL备份工具,支持各种参数选项,使用不同的选项极有可能影响备份处理过程.本文使用我们常规认为合理的备份参数,测试/验证是否存在容易忽视的坑 # 常规备份参数 # mysqldump shell& ...
- joomla安装
最开始我以为是我电脑反映慢.傻傻的等了很久.因为我在sae上面初始化成功了.只是差两张表而已.等了很久很久.也试了好几次.反正就是卡在创建数据表那里.突然我想到在sae初始化数据库的时候有两种模式In ...
- VS Code中Matlab插件安装设置
Install the extension in VS Code Open the command palette using Ctrl+Shift+P Type ext install Matlab ...
- 函数前加static与不加static的区别
1:加了static后表示该函数失去了全局可见性,只在该函数所在的文件作用域内可见 2:当函数声明为static以后,编译器在该目标编译单元内只含有该函数的入口地址,没有函数名,其它编译单元便不能通过 ...