【发布时间】:2017-08-28 20:03:30
【问题描述】:
我在 python 中使用 LZW 算法编码一个简单的文本文件。但是,我意识到我只能使用 write() 函数将字符串写入.txt 文件,该函数本身占用的空间几乎相同。那么是否有可能以某种方式将实际整数写入文件(可能采用不同的格式),
实现适当的压缩?
readfile = open("C:/Users/Dhruv/Desktop/read.txt", "r")
writefile = open("C:/Users/Dhruv/Desktop/write.txt", "w")
content = readfile.read()
length = len(content)
codes = []
for i in range(0, 256) :
codes.append(str(chr(i)))
current_string = ""
for i in range(0, length) :
temp = current_string + content[i]
print(temp)
if temp in codes :
current_string += content[i]
else :
codes.append(current_string + content[i])
writefile.write(str(codes.index(current_string)) + " ")
current_string = str(content[i])
writefile.write(str(codes.index(current_string)) + " ")
readfile.close()
writefile.close();
【问题讨论】:
-
你可能是指二进制文件,以
wb模式打开写入... -
同意@AnttiHaapala,使用“wb”并使用二进制编码发送字节()。见stackoverflow.com/questions/20955543/python-writing-binary
-
我也想存储大于 255 的整数,我该怎么做?另外,我只想将它们作为整数读回
-
您需要一个整数缓冲区来填充可变大小的代码,并且当缓冲区中存在超过 8 位时,您会清除字节。
标签: python compression lzw data-compression