标题:
哈夫曼py程序
[打印本页]
作者:
航123
时间:
2018-6-24 10:59
标题:
哈夫曼py程序
程序可参考
py源程序如下:
import hufcode
import statistic
import six
def decompress():
print("please input youer filename")
inputfilename=input()
f = open(inputfilename,'rb')
filedata1 = f.read()
filedata=bytearray(filedata1)
filesize = f.tell()
#print(filedata)
a1 = filedata[0]
a2 = filedata[1]
a3 = filedata[2]
a4 = filedata[3]
j = 0
j = j|a1
j = j<<8
j = j|a2
j = j<<8
j = j|a3
j = j<<8
j = j|a4
leaf_node_size = j
char_freq = {}
for i in range(leaf_node_size):
c = filedata[4+i*5+0]
a1 = filedata[4+i*5+1]
a2 = filedata[4+i*5+2]
a3 = filedata[4+i*5+3]
a4 = filedata[4+i*5+4]
j=0
j = j|a1
j = j<<8
j = j|a2
j = j<<8
j = j|a3
j = j<<8
j = j|a4
#print (c, j)
char_freq[c] = j
j=0
list1=[]
list_all=[]
for x in char_freq.keys():
list1.append((x,char_freq[x]))
list1.sort()
list_all=[item[0]for item in list1]
#print(list1)
#print(list_all)
nodes = hufcode.createNodes([item[1] for item in list1]) #出现次数
root = hufcode.createHuffmanTree(nodes) #叶子节点
codes = hufcode.huffmanEncoding(nodes,root) #编码
#print(codes)
code1=''
for x in range(leaf_node_size*5+4,filesize):
c = filedata[x]
for i in range(8):
if c&128:
code1 = code1 +'1'
else:
code1 = code1 + '0'
c = c<<1
#print(code1)
newcode=dict(zip(codes,list_all))
print(newcode)
#print(newcode.get('1000'))
#print(bytes((int(newcode.get('1000')),)).decode("ascii"))
i=0
res=''
while i < len(code1)-24:
j = i+1
while j < len(code1): #获取某一字符的code
if code1[i:j] in newcode.keys():
break
j += 1
#print(code1[i:j])
res =res + bytes((int(newcode.get(str(code1[i:j]))),)).decode('ascii')
#print(res)
i = j
sub_code = code1[-16:-8]
last_length = 0
for i in range(8):
last_length = last_length<<1
if sub_code[i] == '1':
last_length = last_length|1
code1=code1[-24:-16]+code1[-8:-8+last_length]
i=0
while i < len(code1):
j = i+1
while j < len(code1): #获取某一字符的code
if code1[i:j] in newcode.keys():
break
j += 1
#print(code1[i:j])
res =res + bytes((int(newcode.get(str(code1[i:j]))),)).decode('ascii')
#print(res)
i = j
print(res)
print("\ndo you want save it? 1/yes,2/no")
ans=input()
ans=int(ans)
if ans==1:
print('please input the filename')
outfilename=input()
out = open(outfilename,"w")
out.write(res)
out.close
else:
pass
复制代码
所有资料51hei提供下载:
霍夫曼.rar
(14.57 KB, 下载次数: 7)
2018-6-24 10:58 上传
点击文件名下载附件
py程序,哈夫曼编码
下载积分: 黑币 -5
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1