由于您使用的是“!” 要开始评论,我假设您使用的是 Fortran 90 或更高版本。
您可以使用正则表达式来查找变量声明。
这是一个查找integer
变量的简单示例:
In [1]: import re
In [2]: integer_re = re.compile('[ ]*integer[^:]*::\s+(.+)')
In [3]: progtext = ''' program average
! Read in some numbers and take the average
! As written, if there are no data points, an average of zero is returned
! While this may not be desired behavior, it keeps this example simple
implicit none
real, dimension(:), allocatable :: points
integer :: number_of_points
real :: average_points=0., positive_average=0., negative_average=0.
write (*,*) "Input number of points to average:"
read (*,*) number_of_points
allocate (points(number_of_points))
write (*,*) "Enter the points to average:"
read (*,*) points
! Take the average by summing points and dividing by number_of_points
if (number_of_points > 0) average_points = sum(points) / number_of_points
! Now form average over positive and negative points only
if (count(points > 0.) > 0) then
positive_average = sum(points, points > 0.) / count(points > 0.)
end if
if (count(points < 0.) > 0) then
negative_average = sum(points, points < 0.) / count(points < 0.)
end if
deallocate (points)
! Print result to terminal
write (*,'(a,g12.4)') 'Average = ', average_points
write (*,'(a,g12.4)') 'Average of positive points = ', positive_average
write (*,'(a,g12.4)') 'Average of negative points = ', negative_average
end program average'''
In [4]: integer_re = re.compile('[ ]*integer[^:]*::\s+(.+)')
In [5]: integer_re.findall(progtext)
Out[5]: ['number_of_points']
其他类型也可以这样做,例如 real:
In [6]: real_re = re.compile('[ ]*real[^:]*::\s+(.*)')
In [7]: real_re.findall(progtext)
Out[7]: ['average_points=0., positive_average=0., negative_average=0.']
您可以优化正则表达式以删除初始化程序并仅获取变量名称。但是拆分可能更容易。
In [8]: real_re.findall(progtext)[0].split()
Out[8]: ['average_points=0.,', 'positive_average=0.,', 'negative_average=0.']
或者您可以使用另一个正则表达式:
In [9]: re.findall('([a-z_]+)', real_re.findall(progtext)[0])
Out[9]: ['average_points', 'positive_average', 'negative_average']