将数据提取出,但是感觉自己编的太麻烦了
123.txt文件是我想从中提取的数据的文件,在其中@符号开始到&符号结束,这区间我所想要的,但是感觉自己编的有一些麻烦,虽然运行出来了结果,但是我感觉应该有更好的写法。希望大家不吝惜赐教,谢谢。Program Getdata
Implicit None
Character(len=125)::str
Real*8,Allocatable::bands1(:),bands2(:),bands3(:),bands4(:),bands5(:),bands6(:),&
bands7(:),bands8(:),kpoint1(:),kpoint2(:),kpoint3(:)
Integer::i,ierr,count,n
Open(11,file=' 123.txt' )
Open(12,file=' shuju.txt' )
count=0
Do
Read(11," ( a125 ) ",iostat=ierr) str
If(ierr/=0) Exit
If( str(11:13)== 'k = ' ) Then
count=count+1
End If
End Do
Allocate(bands1(count))
Allocate(bands2(count))
Allocate(bands3(count))
Allocate(bands4(count))
Allocate(bands5(count))
Allocate(bands6(count))
Allocate(bands7(count))
Allocate(bands8(count))
Allocate(kpoint1(count))
Allocate(kpoint2(count))
Allocate(kpoint3(count))
Rewind(11)
i=1
Do
Read(11,' (a125) ' ,iostat=ierr) str
If(ierr/=0) Exit
If(str(11:13)== 'k =' ) Then
Read(str(14:35),*) kpoint1(i),kpoint2(i),kpoint3(i)
Read(11,*)
Read(11,' (a125) ',iostat=ierr) str
Read(str(5:75),*) bands1(i),bands2(i),bands3(i),bands4(i),&
bands5(i),bands6(i),bands7(i),bands8(i)
i=i+1
End If
End Do
Do i=1,count
Write(12,"(a3,3f7.4,1x,a9,8(f7.4,1x)) ") 'k=',kpoint1(i),kpoint2(i),kpoint3(i),'bands(ev) ',&
bands1(i),bands2(i),bands3(i),bands4(i),bands5(i),bands6(i),bands7(i),bands8(i)
End Do
Close(11)
Close(12)
End Program Getdata
Program Getdata
Implicit None
Character(len=125)::str
Integer , parameter :: NBOUNDS = 8
Integer , parameter :: NPOINTS = 3
Real(kind=8) , Allocatable :: bands(:,:) , kpoint(:,:)
Integer :: i , j , ierr , n
Open(11,file='123.txt' )
Open(12,file='shuju.txt' )
Do
Read( 11 , "(a125)" , iostat = ierr ) str
If( ierr /= 0 ) goto 9
str = adjustl(str)
If( str(1:1) == '@' ) exit
End Do
j = 0
Do
If ( index( str , "k =" ) > 0 ) j = j + 1
Read( 11 , "(a125)" , iostat = ierr ) str
If( ierr /= 0 ) goto 9
str = adjustl(str)
If ( str(1:1) == '&' ) exit
End Do
n = j
Allocate( bands ( NBOUNDS , n ) )
Allocate( kpoint( NPOINTS , n ) )
Rewind(11)
Do
Read( 11 , "(a125)" , iostat = ierr ) str
If( ierr /= 0 ) goto 9
str = adjustl(str)
If( str(1:1) == '@' ) exit
End Do
j = 1
Do
i = index( str , "k =" )
If ( i > 0 ) then
Read( str(i+3:) , *) kpoint(:,j)
Read( 11 , * ) bands(:,j)
j = j + 1
If ( j > n ) exit
End If
Read( 11 , '(a125)' , iostat = ierr ) str
End Do
Do i = 1 , n
Write(12,"(a3,3f7.4,1x,a9,8(f7.4,1x)) ") 'k=',kpoint(:,i),'bands(ev) ',bands(:,i)
End Do
9 Close(11)
Close(12)
End Program Getdata 谢谢老大,你的写法很好,避免了大量充斥近来的allocate,同时也非常严谨的考虑到了其他情况,即go to 9。难得看见老大用go to 语句,不过虽然用了,没有破坏整个程序的结构,赞。学习了。
页:
[1]