gpt4 book ai didi

r - 如何从 r 中的 gzip 文件读取行?

转载 作者:行者123 更新时间:2023-12-03 09:38:06 30 4
gpt4 key购买 nike

我需要从 gzip 文件中小批量(比如一次 100 行)读取行 这是一个使用 gzip 压缩的文本文件 .我使用小批量,因为每行都非常长。

但是我无法使用这样的东西(我认为缓冲区没有更新):

in.con <- gzfile("somefile.txt.gz")
for (i in 1:100000) {
chunk <- readLines(in.con,n = 100)
# if you inspect chunk in each loop step, say with a print
# you will find that chunk updates once or twice and then
# keeps printing the same data.
}
close(in.con)

我如何完成类似的事情?

笔记:
  • 对于小文件,这将起作用。
  • 您将需要一个非常大的文件,并且当您尝试多次读取它时——您将看到块变量不会更新
  • 我认为这是因为底层扫描对 gzip 文件不可靠
  • i 变量只是为了限制循环——不需要引用 i
  • 一些评论似乎在说该代码不适用于文本文件——我发布的结果不是这样:

  • .
    in.con <- file("some.file.txt", "r", blocking = FALSE)
    while(TRUE) {
    chunk <- readLines(in.con,n = 2)
    if (length(chunk)==0) break;
    print(chunk)
    }
    close(in.con)

    导致输出:
    [1] "1" "2"
    [1] "3" "4"
    [1] "5" "6"
    [1] "7" "8"
    [1] "9" "10"

    我的版本信息是:
    platform       x86_64-apple-darwin15.6.0   
    arch x86_64
    os darwin15.6.0
    system x86_64, darwin15.6.0
    status
    major 3
    minor 4.1
    year 2017
    month 06
    day 30
    svn rev 72865
    language R
    version.string R version 3.4.1 (2017-06-30)
    nickname Single Candle

    最佳答案

    这是 gzfile() 中的一个错误.对于大文件,如果没有 open指定参数,它将一遍又一遍地读取同一行。

    > incon <- gzfile(zfile)
    > readLines(incon,1)
    [1] First line
    > readLines(incon,1)
    [1] First line

    即使与 open参数指定,它只会导致错误。
    > incon <- gzfile(zfile,open="r")
    > line <- readLines(incon,1)
    Warning message:
    In readLines(incon, 1) :
    seek on a gzfile connection returned an internal error

    解决方案 :作为一种解决方法,可以改用常规 file()以二进制读取模式连接并将其包装在 gzcon() 中:
    > incon <- gzcon(file(zfile,open="rb"))
    > readLines(incon,1)
    [1] First line
    > readLines(incon,1)
    [1] Second line

    关于r - 如何从 r 中的 gzip 文件读取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665496/

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