在Julia中读取特定行

问题描述

由于我是朱莉娅(Julia)的新手,所以有时您会遇到一些明显的问题。 这次我不知道如何从文件中读取某些数据,即:

...
      stencil: half/bin/3d/newton
      bin: intel
Per MPI rank memory allocation (min/avg/max) = 12.41 | 12.5 | 12.6 Mbytes

Step TotEng PotEng Temp Press Pxx Pyy Pzz Density Lx Ly Lz c_Tr 

  200000    261360.25    261349.16    413.63193    2032.9855    -8486.073    4108.1669    
  200010    261360.45    261349.36    413.53903    22.925126   -29.762605    132.03134   
  200020    261360.25    261349.17    413.46495    20.373081   -30.088775     129.6742   


Loop

我想要的是从“ Step”(从200010开始的文件,可以是另一个数字-我有很多文件在同一位置但从不同的整数开始)之后的第三行读取此文件将到达“循环”。请问你能帮帮我吗?我被堆积了-我不知道如何结合朱莉娅的不同选择来做到这一点...

解决方法

这是一种解决方案。它使用eachline遍历各行。循环跳过标题和任何空行,并在找到Loop行时中断。要保留的行以向量形式返回。您可能需要根据确切的文件格式来修改标头和/或结束标记的检测。

julia> function f(file)
           result = String[]
           for line in eachline(file)
               if startswith(line,"Step") || isempty(line)
                   continue # skip the header and any empty lines
               elseif startswith(line,"Loop")
                   break # stop reading completely
               end
               
               push!(result,line)
           end
           return result
       end
f (generic function with 2 methods)

julia> f("file.txt")
3-element Array{String,1}:
 "200000 261360.25 261349.16 413.63193 2032.9855 -8486.073 4108.1669"
 "200010 261360.45 261349.36 413.53903 22.925126 -29.762605 132.03134"
 "200020 261360.25 261349.17 413.46495 20.373081 -30.088775 129.6742"