如何在Julia中逐行读取文件?


18

如何打开文本文件并逐行阅读?我对以下两种情况感兴趣:

  1. 一次获取数组中的所有行。
  2. 一次处理每一行。

对于第二种情况,我不想一次将所有行都保留在内存中。

Answers:


25

以行数组的形式一次将文件读入内存只是对readlines函数的调用:

julia> words = readlines("/usr/share/dict/words")
235886-element Array{String,1}:
 "A"
 "a"
 "aa"
 
 "zythum"
 "Zyzomys"
 "Zyzzogeton"

默认情况下,这会丢弃换行符,但是如果要保留它们,则可以传递关键字参数keep=true

julia> words = readlines("/usr/share/dict/words", keep=true)
235886-element Array{String,1}:
 "A\n"
 "a\n"
 "aa\n"
 
 "zythum\n"
 "Zyzomys\n"
 "Zyzzogeton\n"

如果您已经打开了文件对象,也可以将其传递给readlines函数:

julia> open("/usr/share/dict/words") do io
           readline(io) # throw out the first line
           readlines(io)
       end
235885-element Array{String,1}:
 "a"
 "aa"
 "aal"
 
 "zythum"
 "Zyzomys"
 "Zyzzogeton"

这演示了该readline函数,该函数从打开的I / O对象读取一行,或者在给定文件名时打开文件并从中读取第一行:

julia> readline("/usr/share/dict/words")
"A"

如果您不想一次全部加载文件内容(或者正在处理流式数据,例如从网络套接字获取数据),则可以使用该eachline函数来获取一次生成一行的迭代器:

julia> for word in eachline("/usr/share/dict/words")
           if length(word) >= 24
               println(word)
           end
       end
formaldehydesulphoxylate
pathologicopsychological
scientificophilosophical
tetraiodophenolphthalein
thyroparathyroidectomize

eachline函数也可以像一样readlines,被赋予打开的文件句柄以读取行。您还可以通过打开文件并readline重复调用来“滚动自己的”迭代器:

julia> open("/usr/share/dict/words") do io
           while !eof(io)
               word = readline(io)
               if length(word) >= 24
                   println(word)
               end
           end
       end
formaldehydesulphoxylate
pathologicopsychological
scientificophilosophical
tetraiodophenolphthalein
thyroparathyroidectomize

这等同于eachline为您提供的服务,很少需要自己执行此操作,但是如果需要,功能就在那里。有关逐字符读取文件的更多信息,请参见以下问答:如何使用julia一次读取一个.txt文件的每个字符?

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.