gpt4 book ai didi

python - python 中的基本 lzw 压缩帮助

转载 作者:行者123 更新时间:2023-11-28 22:04:39 26 4
gpt4 key购买 nike

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

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

这是我所拥有的:

import lzw

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

任何类型的帮助或指示将不胜感激!

谢谢 =)

最佳答案

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

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

还有什么不明白的地方吗?

这是一个例子:

python

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

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

关于python - python 中的基本 lzw 压缩帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6834388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com