RLE压缩算法

时间:2015-03-09 21:32:20

标签: python compression

我正在尝试运行这个简单的RLE Run Length Encoding压缩算法。我有什么选择可以返回结果?

def decode(text_decode):
    decoded_text = ""
    length = len(text_decode)
    if length == 0:
        decoded_text = ""
    elif length == 1:
        decoded_text = text_decode
    else:
        i = 1
        while i < length:
            next_block =""
            for j in range(0, int(text_decode[i])):
                next_block += text_decode[i - 1]
            decoded_text += next_block
            i += 2
    return decoded_text

2 个答案:

答案 0 :(得分:1)

您还没有充分描述压缩文本的格式 - 所以我通过查看您的代码并将其与我在网上搜索的相关实现进行比较来猜测。

这里有一对似乎可以协同工作的功能:

def encode(input_string):
    """ Simple run-length encoder.

    Modified version of code at http://rosettacode.org/wiki/Run-length_encoding#Python
    """
    count = 1
    prev = ''
    lst = []
    for character in input_string:
        if character != prev:
            if prev:
                entry = (prev,count)
                lst.append(entry)
            count = 1
            prev = character
        else:
            count += 1
    else:
        entry = (character,count)
        lst.append(entry)
    return ''.join(chr(cnt)+ch for (ch, cnt) in lst)

def decode(encoded_text):
    """ Simple run-length decoder. """
    chars = []
    a = iter(encoded_text)
    for (cnt, ch) in zip(a, a):
        chars.append(ch * ord(cnt))
    return ''.join(chars)

word = "aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa"
rle_text = encode(word)
print(len(word))  # -> 32
print(len(rle_text)) # -> 12
print(decode(rle_text))  # -> "aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa"

答案 1 :(得分:0)

像这样,您可以应用算法并运行它。 您还可以选择要转换的&#34;

的文本
texte = raw_input("Your text to compress: ")
text_rle = decoded(texte)
print(text_rle)