1

このようなデータセットを読み込もうとしています

DATE,TIME,val
1/1/2001,1:00:00,0

プログラムで

program main
implicit none

real :: val
character(len=8) :: date
character(len=7) :: time
open(1,file='data.csv',status='old')
read(1,*) ! header
read(1,fmt=100)date,time,val
100 FORMAT (A,1x,A,1x,F3.1)
end program

日付と時刻が常に 8 文字または 7 文字である場合、これはすべて問題ありませんが、たとえば、そうではありません。

 4/21/2001,19:00:00,0

例の日付、時刻、および val 行の両方を読み取るには、fortran の形式をどのように宣言すればよいですか?

ありがとうございました

4

2 に答える 2

7

行全体data, time, valueを1つの文字列に読み取り、それを処理して個々の要素を抽出することができます。

program main
implicit none

real :: val
character(len=10) :: date
character(len=8) :: time

character(len=100) :: line
integer :: n1, n2, end

open(1, file='data.csv', status='old')

! Read entire second line into `line`, ignoring the header
read(1,*) ! header
read(1,'(A100)') line

! Determine locations of the first and last comma in `line` and the
! end of the line:
n1  = index(line, ',')
n2  = index(line, ',', back=.True.)
end = len_trim(data)

! Split line up according to position of commas and assign to 
! appropriate variables
date = data(1:n1-1)
time = data(n1+1:n2-1)
read(data(n2+1:end), *) val ! Internal read, for converting from string to float

end program main

これは質問のサンプルデータに非常に特化していることに注意してください。ただし、このコードを一般化するのはそれほど難しいことではありません。

于 2012-07-03T13:42:35.053 に答える
0

使用している「データ」変数を定義していません。このソリューションのもう 1 つの問題は、すべての変数が文字として固まってしまい、分析に役立たない可能性があることです。

于 2013-11-20T22:43:08.567 に答える