【问题标题】:Write numbers to a file instead of string for data compression?将数字写入文件而不是字符串以进行数据压缩?
【发布时间】: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


【解决方案1】:

如果您的数据可以表示为 Numpy 数组,则以下函数可以将其写为 .txt 文件中的整数:

import numpy as np
def writer(_hd, _data):
    out_file_name = str(_hd) + '.csv'
    np.savetxt(out_file_name, _data, fmt='%i')
    return None

其中 _hd 是文件名,_data 是 numpy 数组。 fmt='%i' 将数据保存为整数;其他选项也可用here

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2020-05-24
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多