有没有办法在python中用数字和字母进行Rle压缩

2024-04-25 09:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用python做一个rle压缩算法,但是我的代码无法解压数字

我在python3.7中尝试了format命令,但是它给了我一个语法错误

# This program allows you to encode and decode lines of text using RLE
# First function allows a line of data to be encoded

def rle_encode(data):
    encoding = ''
    prev_char = ''
    count = 1

     if not data: return ''

    for char in data:
        # If the prev and current characters
        # don't match...
        if char != prev_char:
            # ...then add the count and character
             # to our encoding
            if prev_char:
                 encoding += str(count) + prev_char
                #encoding = ("{:02d}".format(encoding)) -this is what 
#isn't working
            count = 1
            prev_char = char
        else:
            # Or increment our counter
            # if the characters do match
            count += 1
    else:
        # Finish off the encoding
        encoding += str(count) + prev_char

    return encoding

#Now test the code for encoding using RLE

print (rle_encode('AAAABBFFFFF55555'))

#Second function allows a line of lossless compressed data to be decoded

def rle_decode(data):
    decode = ''
    count = ''
    for char in data:
        # If the character is numerical...
        if char.isdigit():
            # ...append it to our count
            count += char
        else:
            # Otherwise we've seen a non-numerical
            # character and need to expand it for
            # the decoding
            decode += char * int(count)
            count = ''
    return decode

#Now test the code for decoding using RLE

print (rle_decode('4A2B5F141'))

Tags: andofthetofordataifcount