ubuntu

Ubuntu Fortran如何进行文本分析

小樊
46
2025-12-20 08:36:12
栏目: 智能运维

Ubuntu 下用 Fortran 做文本分析的实用路线

一 环境准备与编译运行

二 基础文本读写与行级解析

program word_split_sum
  implicit none
  character(len=:), allocatable :: line
  character(len=256), allocatable :: toks(:)
  integer :: i, n, ios, ntok
  real :: x, sum_x, mean_x
  integer, parameter :: max_tok = 256

  open(newunit=10, file='data.txt', status='old', action='read', iostat=ios)
  if (ios /= 0) stop 'Cannot open data.txt'

  sum_x = 0.0; n = 0
  allocate(toks(max_tok))

  do
    read(10, '(A)', iostat=ios) line
    if (ios /= 0) exit
    line = trim(line)

    ! 简单空白切分
    ntok = 0
    do i = 1, len_trim(line)
      if (line(i:i) /= ' ' .and. line(i:i) /= char(9)) then
        if (ntok == 0 .or. index(' '//char(9), line(i:i)) /= 0) then
          ntok = ntok + 1
          toks(ntok) = ''
        end if
        toks(ntok) = trim(toks(ntok)) // line(i:i)
      end if
    end do

    ! 转数值并累计
    do i = 1, ntok
      read(toks(i), *, iostat=ios) x
      if (ios == 0) then
        sum_x = sum_x + x
        n = n + 1
      end if
    end do
  end do
  close(10)

  if (n > 0) then
    mean_x = sum_x / n
    print '("Count=",I0,"  Sum=",F12.6,"  Mean=",F12.6)', n, sum_x, mean_x
  else
    print *, 'No numbers found.'
  end if

  deallocate(toks)
end program word_split_sum

三 进阶处理与常用算法

四 实用建议与排错要点

0
看了该问题的人还看了