【问题标题】:uncompress gz file in R, and do a bitewise operation在 R 中解压缩 gz 文件,并进行逐位操作
【发布时间】:2020-10-18 22:10:15
【问题描述】:

目前我有一个 csv 文件的 .gz 文件。我想解压缩它。

难点在于.gz文件解压后,需要逐位操作才能得到正确的格式。

我在 python 中有可以工作的代码,但我正在努力将其转换为 R

def uncompress_file(file_location_gz, file_location_save):

    with open(file_location_gz, "rb") as f:
      data = f.read()
    data2 = gzip.GzipFile(fileobj=BytesIO(data),
                         mode='rb').read()
    data2 = bytearray(data2)
    for i in range(len(data2)):
      data2[i] ^= 0x95
    with open(file_location_save, 'wb') as f_out:
     f_out.write(data2)

任何帮助或建议都会很有帮助。

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: python r compression gzip bitwise-operators


【解决方案1】:

这是函数在 R 中的样子

decompress_xor <- function(file_in, file_out, xor_byte = 0x95) {
  gfin <- gzfile(file_in, "rb")
  bytes <- readBin(gfin, "raw", file.info(file_in)$size)
  close(gfin)
  decoded_bytes <- as.raw(bitwXor(as.numeric(bytes), xor_byte))
  rawToChar(decoded_bytes)
  writeBin(decoded_bytes, file_out)
}

我们使用gzfile() 来处理解压缩,然后将数据作为原始字节读取。我们使用 xor 转换这些字节,然后将这些字节写回。

【讨论】:

  • 非常感谢@MrFlick 成功了!!我已经坚持了一段时间。再次感谢您。
  • @dwt 如果答案有帮助。请随时点击左侧的复选标记accept the answer :-) 每个帖子只能接受一个答案。