从txt读取科学格式的数字 [英] Read scientific formatted numbers from txt

查看:130
本文介绍了从txt读取科学格式的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从txt文件中读取并存储科学格式的数字,该txt文件经过格式化,并且数字由制表符分隔.

I would like to read and store scientific formatted numbers from a txt file, which is formatted and the numbers are separated by tabulator.

这是我到目前为止所拥有的:

This is what I have so far:

IMPLICIT NONE

REAL,ALLOCATABLE,DIMENSION(2)    :: data(:,:)       
INTEGER              :: row,column
INTEGER              :: j,i
CHARACTER(len=30)        :: filename
CHARACTER(len=30)        :: format

filename='data.txt'
open(86,file=filename,err=10)
write(*,*)'open data file'   
read(86, *) row
read(86, *) column

allocate(data(row,column))

format='(ES14.7)'   

do i=1,row
  read(86,format) data(i,:)
enddo

close(86)

这是txt文件的外观:

This is how the txt file looks like:

200
35
2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35  ...

问题在于,它无法从txt读取正确的值并将其存储到数据变量中.是引起问题的格式吗?

The problem is that it doesn't read and store the correct values from the txt to the data variable. Is it the format causing the problem?

在这种情况下,我还想知道如何计算列数. (我可以在for循环中使用read(86,*)来计算行数.)

I would also like to know how to count the number of columns in this case. (I can count the rows by using read(86,*) in a for loop.)

推荐答案

是的,您的格式不利于显示的数据.更好的应该是这样的read(99,'(6(E11.4,X))') myData(i,:).

Yes, your format is not good for the data you show. Better one should be like that read(99,'(6(E11.4,X))') myData(i,:).

但是,我不确定您是否真的需要在阅读时使用格式.

However, I am not sure if you really need to use format at your reading at all.

下面的示例与您尝试执行的操作非常接近,并且无论是否带有格式,它都可以正常工作.

Following example pretty close to what you are trying to do, and it is working bot with and without format.

program readdata
  implicit none
  real, allocatable :: myData(:,:)
  real              :: myLine
  integer           :: i, j, myRow, myColumn
  character(len=30) :: myFileName
  character(len=30) :: myFormat

  myFileName='data.dat'

  open(99, file=myFileName)
  write(*,*)'open data file'
  read(99, *) myRow
  read(99, *) myColumn

  allocate(myData(myRow,myColumn))

  do i=1,myRow
    read(99,*) myData(i,:)
    !read(99,'(6(E11.4,X))') myData(i,:)
    print*, myData(i,:)
  enddo

  close(99)

end program readdata

为了进行测试,我假设文件中总是有行和列,如您所给,所以我的测试数据如下.

To test, I assumed that you have rows and columns always in the file, as you give, so my test data was following.

2
6
2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35
2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35

如果您真的有兴趣使用某种格式读取文件,并且列数不是恒定的,则根据变量可能需要一种格式,请参阅相关讨论

If you are really interested to read your files with a format and if the number of columns are not constant you may need a format depending on a variable, please see related discussions here.

这篇关于从txt读取科学格式的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆