Python implementation of compression software based on Huffman coding

Source: Internet
Author: User
Tags object serialization unpack

Huffman coding is the use of greedy algorithm for text compression algorithm, the algorithm idea is the number of characters in the first statistical file, save to the array, and then the characters in ascending order of the number of times, the smallest selection of two elements to join the formation of a subtree, the number of sub-tree is equal to two nodes of the sum of the number of Then delete the two elements from the array, put the subtree into the array, reorder, repeat the above steps. To understand the pressure, the length of the Huffman encoded mapping table is first filled into the file during compression, the serialized string of the table, the length of the last set after the encoded string is grouped (encoded string length modulo the length of the packet), and finally the encoded string is populated. In this algorithm, one byte, 8 bits as the grouping length, the encoded binary string one by one is grouped. The code is as follows:

__author__ = ' Linfuyuan ' import structimport pickletype = Int (raw_input (' Please input ' of the type number (0 for compress, 1 for        Decompress): ') file = raw_input (' Please input the filepath: ') class Node:def __init__ (self): Self.value = ' Self.left = None Self.right = None Self.frequency = 0 Self.code = ' # Let the unique value is th E key in the Mapdef Change_value_to_key (huffmap): map = {} for (key, value) in Huffmap.items (): map[value] = Key return MAPIF type = = 0:origindata = ' # count the frequency of each letter Lettermap = {} def give_co        De (node): If Node.left:node.left.code = '%s%s '% (Node.code, ' 0 ') Give_code (node.left) If Node.right:node.right.code = '%s%s '% (Node.code, ' 1 ') Give_code (node.right) def Print_code (node): If not node.left and not Node.right:print "%s%s"% (Node.value, node.code) if Node.left : Print_code (Node.left) if Node.right:print_code (node.right) def save_code (Map, node): If not node.left an        D not Node.right:map[node.value] = Node.code if Node.left:save_code (map, Node.left)            If Node.right:save_code (map, Node.right) with open (file) as F:for line in F.readlines ():                Origindata + = line to J in Line:if Lettermap.get (j): Lettermap[j] + = 1 ELSE:LETTERMAP[J] = 1 nodelist = [] for (key, value) in Lettermap.items (): nod E = Node () Node.value = key Node.frequency = value nodelist.append (node) nodelist.sort (Cmp=lambda N1, n2:cmp (N1.frequency, n2.frequency)) for I in Range (len (nodelist)-1): Node1 = nodelist[0] Node2 = n  ODELIST[1] node = node () Node.left = Node1 Node.right = Node2 node.frequency = node1.frequency      + node2.frequency  Nodelist[0] = node Nodelist.pop (1) nodelist.sort (Cmp=lambda N1, n2:cmp (N1.frequency, n2.frequency)) # Give the code root = Nodelist[0] Give_code (root) Huffman_map = {} # Save the node code to a map Save_code (h Uffman_map, root) Code_data = "for letter in Origindata:code_data + = Huffman_map[letter] Output_data = ' F = open ('%s_compress '% file, ' WB ') huffman_map_bytes = Pickle.dumps (huffman_map) f.write (Struct.pack (' I ', le N (huffman_map_bytes))) F.write (Struct.pack ('%ds '% len (huffman_map_bytes), huffman_map_bytes)) F.write (Struct.pack ( ' B ', Len (code_data)% 8))) for I in range (0, Len (code_data), 8): If i + 8 < Len (code_data): F.write (Struct.pack (' B ', int (code_data[i:i + 8], 2)) Else: # padding F.write (struct.pack (' B ', int (c Ode_data[i:], 2)) F.close () print ' finished compressing ' if type = = 1:f = open (file, ' RB ') size = Struct.unpa    CK (' I ', F.read (4)) [0]Huffman_map = Pickle.loads (f.read (size)) left = Struct.unpack (' B ', F.read (1)) [0] data = F.read (1) datalist = [] While not data = = ": Bdata = Bin (struct.unpack (' B ', data) [0]) [2:] Datalist.append (bdata) data = f. Read (1) f.close () for I in Range (Len (DataList)-1): datalist[i] = '%s%s '% (' 0 ' * (8-len (datalist[i))), Da    Talist[i]) datalist[-1] = '%s%s '% (' 0 ' * (Left-len (datalist[-1])), datalist[-1]) Encode_data = '. Join (DataList) Current_code = "Huffman_map = Change_value_to_key (huffman_map) f = open ('%s_origin '% file, ' W ') for letter In Encode_data:current_code + = Letter If Huffman_map.get (current_code): F.write (Huffman_map[curr Ent_code]) Current_code = ' f.close () print ' Finished decompressing ' raw_input (' Press any key to Q Uit ')

The code is useful to pickle modules for object serialization, as well as a struct module for reading and writing binary files.

Because the computation of the algorithm in the most of the ground is the loop? Nested sorting, the time complexity of the algorithm is O (n2logn).

after compression, the size of the file is small, respectively. 110KB and the 931KB . Originally?? For 190KB and 2.1MB, the compression effect is obvious.

Hope to be useful to everyone.

Python implementation of compression software based on Huffman coding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.