Fortran 文本解析问题

问题描述 投票:0回答:1

我在数据中间有以下行:

Lattice="14.118460851 0.0 0.0 0.0 14.296182713 0.0 0.0 0.0 13.970592923" Properties=species:S:1:pos:R:3:forces:R:3 energy=-1558.14096522 stress="0.01917032092545686 0.004679034697346147 -0.002715150092396106 0.004679034697346147 0.02270959988283459 -0.0033934086475967138 -0.002715150092396106 -0.0033934086475967138 0.02437748091748962" free_energy=-1558.0193295 pbc="T T T"

在这一行中,每个关键字都包含特定的属性。

在这里,我想读取这一行并为变量或数组定义一些值。我希望在 'Lattice="' 之后读取 9 个实数并将它们存储为 a, b, c, d, e, f,我希望在 'energy=' 之后读取一个实数并将其存储为 g.

但我不知道如何编写 Fortran 脚本来读取和识别“Lattice=”和“energy=”,然后选择 9 或下一个数字。

如何使用 Fortran 来做到这一点?

parsing fortran
1个回答
0
投票

你有一个简单的解析问题。尽管字符串的形式迫切需要使用

namelist
。 这是一个程序,向您展示如何使用 Fortran 的
INDEX
内部子程序。

program foo

   implicit none
   !
   ! buf must be large enough to hold the entire line.
   !   
   character(len=512) buf
   integer fd, i, j
   real a(9)
   !
   ! Assumes the text is in a file named 'a.txt'
   !
   open(newunit=fd,file='a.txt',status='old')
   read(fd,'(A)') buf
   close(fd)

   i = index(buf, 'Lattice="')
   if (i == 0) stop 'Lattice=" not found'
   !
   ! Add nine to location the first character after ".
   !
   i = i + 9

   j = index(buf(i:), '"') + i - 2  ! Subtract 2 to be in front of ".
   read(buf(i:j), *) a
   print *, a(1)
   
end program foo
© www.soinside.com 2019 - 2024. All rights reserved.