For this week’s assignment, I wrote a simple run-length encoder for ASCII text in Python. It counts the number of characters in a run of characters and encodes the results in another ASCII string. In addition, it also appends a special character (a slash) whenever a character is a numeric digit, so that there’s no confusion between which characters are actual data from the input file, and which are descriptions of run lengths.
I’ve written an encoder and decoder. As an example of what the output looks like, calling the function:
Returns this result:
And the decoder reverses this process.
Here’s the code:
# Python Run-Length Encoder # Matthew Kaney 2015 def encode(input): output = '' lastChar = '' counter = 0 for character in input: if character == lastChar: counter += 1 else: if counter > 0: # Add an escape character ('/') for digits and slashes if (lastChar >= '0' and lastChar <= '9') or lastChar == '/': lastChar = '/' + lastChar output += str(counter) + lastChar counter = 1 lastChar = character # Append the last character if (lastChar >= '0' and lastChar <= '9') or lastChar == '/': lastChar = '/' + lastChar output += str(counter) + lastChar return output def decode(input): output = '' counter = '' escapeCharacter = False for character in input: if escapeCharacter: output += character * int(counter) counter = '' escapeCharacter = False elif character >= '0' and character <= '9': counter += character elif character == '/': escapeCharacter = True else: output += character * int(counter) counter = '' return output
The comments are closed.