Created
April 28, 2020 22:23
-
-
Save cosinekitty/3dd557ec3cb25eb271980f19986776e1 to your computer and use it in GitHub Desktop.
Compressor based on simple Huffman encoding of characters in the input.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from huffman import HuffmanEncoder | |
| from binary_tools import BitBuffer | |
| class Compressor: | |
| def Name(self): | |
| return 'letters' | |
| def Compress(self, words): | |
| charRoot = self._HuffmanCode(words) | |
| charCode = charRoot.MakeEncoding() | |
| buf = self._Encode(words, charCode) | |
| source = "Char=" + charRoot.SourceCode() + "\n" | |
| source += "NumChars={:d}\n".format(sum(1+len(w) for w in words)-1) | |
| source += "Bits=r'''\n" + buf.Format() + "'''\n" | |
| return source | |
| def _Encode(self, words, charCode): | |
| buf = BitBuffer() | |
| for w in words: | |
| for c in w: | |
| buf.Append(charCode[c]) | |
| buf.Append(charCode['\n']) | |
| return buf | |
| def _HuffmanCode(self, words): | |
| charHuff = HuffmanEncoder() | |
| for w in words: | |
| for c in w: | |
| charHuff.Tally(c) | |
| charHuff.Tally('\n') | |
| return charHuff.Compile() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment