IDL读取文本格式文件

今天遇到一个很常见的将文本文件的数据读出的问题

文本文件a.txt

2011-12-16 09:58:49
数据收发方式:单独接收通讯数据
数据发送端口:Com 1 19200,N,8,1 数据接收端口:Com 1 19200,N,8,1
接收数据:020007,2.1,0,-99.0,0
020015,2.4,0,-99.0,0
020023,2.7,0,-99.0,0
020031,3.0,0,-99.0,0
020039,3.3,0,-99.0,0
020047,3.6,0,-99.0,0
020055,3.9,0,-99.0,0

2011-12-16 17:59:19
数据收发方式:单独接收通讯数据
数据发送端口:Com 1 19200,N,8,1 数据接收端口:Com 1 19200,N,8,1
接收数据:100007,2.1,0,-99.0,0
100015,2.4,0,-99.0,0
100023,2.7,0,-99.0,0
100031,3.0,0,-99.0,0
100039,3.3,0,-99.0,0
100047,3.6,0,-99.0,0
100055,3.9,1,-04.6,1
100103,4.2,1,-06.4,1
100111,4.5,0,-99.0,0
023319,9.3,1,-04.4,1
023327,9.6,1,-02.6,1
023335,9.9,1,-05.2,1
023343,10.2,1,-04.7,1
023351,10.5,1,-02.5,1
023359,10.8,1,-00.5,1
023407,11.1,1, 04.3,1
023415,11.4,1,-00.2,1
023423,11.7,1,-05.6,1
023431,12.0,1, 06.7,1
023439,12.3,1, 10.6,1
023447,12.6,1, 10.8,1
023455,12.9,1, 06.9,1
023503,13.2,1, 05.7,1
023511,13.5,1, 08.5,1
023519,13.8,1, 07.5,1
023527,14.1,1, 07.5,1

真是神马格式都有…

调整IDL代码格式为GB2312

pro test
  openr,lun,'a.txt',/get_lun
  str=''
  templet={area1:'',area2:0.0,area3:0,area4:0.0,area5:0}
errrestart:  while (~EOF(lun)) do begin
    readf,lun,str
    ON_IOError,errrestart
    if (n_elements(str) gt 0) then begin
      if (strpos(str,'接收数据:') ne -1) then begin
        str=strmid(str,10)
      endif
        reads,str,templet,format='(%"%6s,%f,%d,%f,%d")'
        if (n_elements(output) eq 0) then begin 
          output=templet
        endif else begin
          output=[output,templet]
        endelse 
    endif 
  endwhile
  print,output
end

首先建立一个模板templet,然后一行一行地读文本文件,用带有format的reads读取固定格式的一行,用ON_IOError屏蔽reads不符合模板的行时发出的错误命令。

posted on 2012-01-06 14:51  lartely  阅读(7133)  评论(1编辑  收藏  举报

导航