【问题标题】:Basic lzw compression help in pythonpython中的基本lzw压缩帮助
【发布时间】:2011-10-13 15:29:47
【问题描述】:

我只是想写一个非常基本的脚本,它会接受一些输入文本并用 lzw 压缩它,使用这个包:http://packages.python.org/lzw/

我以前从未尝试过使用 python 进行任何编码,并且非常困惑 =( - 除了包信息之外,我也找不到任何关于它的在线文档。

这是我所拥有的:

import lzw

file = lzw.readbytes("collectemailinfo.txt", buffersize=1024)
enc = lzw.compress(file)
print enc

任何帮助或任何指示都将不胜感激!

谢谢 =)

【问题讨论】:

  • 你的东西有问题吗?您可能无法打印它并期望它是人类可读的,但您可以将它保存在某个地方。你的代码在我看来是正确的。
  • 啊,对了,谢谢-我确实尝试删除“print enc”并将其替换为“lzw.writebytes(output.txt, enc)”,但对此也不满意 =(

标签: python encode lzw


【解决方案1】:

这里是包 API:http://packages.python.org/lzw/lzw-module.html

您可以阅读压缩解压缩的伪代码here

你还有什么不明白的吗?

这是一个例子:

Python

在这个版本中,dicts 包含混合类型的数据:

def compress(uncompressed):
    """Compress a string to a list of output symbols."""

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    w = ""
    result = []
    for c in uncompressed:
        wc = w + c
        if wc in dictionary:
            w = wc
        else:
            result.append(dictionary[w])
            # Add wc to the dictionary.
            dictionary[wc] = dict_size
            dict_size += 1
            w = c

    # Output the code for w.
    if w:
        result.append(dictionary[w])
    return result



def decompress(compressed):
    """Decompress a list of output ks to a string."""

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    w = result = compressed.pop(0)
    for k in compressed:
        if k in dictionary:
            entry = dictionary[k]
        elif k == dict_size:
            entry = w + w[0]
        else:
            raise ValueError('Bad compressed k: %s' % k)
        result += entry

        # Add w+entry[0] to the dictionary.
        dictionary[dict_size] = w + entry[0]
        dict_size += 1

        w = entry
    return result

如何使用:

compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)

输出

['T', 'O', 'B', 'E', 'O', 'R', 'N', 'O', 'T', 256, 258, 260, 265, 259, 261, 263]
TOBEORNOTTOBEORTOBEORNOT

注意:本例取自here

【讨论】:

  • 感谢您的帮助,是的,我一直在尝试使用包 API 站点中的信息,但到目前为止失败了 =( 关于第二个链接,我是否应该只翻译伪代码进入python并使用它?
  • 我必须正确通读它并尝试理解发生了什么,这显然比我最初想象的要复杂得多——我认为一个简单的 5-6 行脚本就可以涵盖它!我现在就去,非常感谢saher!
  • 没问题。很高兴我能帮助你。如果您对代码有任何疑问,我也可以帮助您理解代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
相关资源
最近更新 更多