2013-02-28 87 views
0

我有一个文件看起来像这样:Fortran语言:格式化读

startSpecifier 

( 251)-0.0110365 ( 168)-0.0110365 (1267) 0.0108601 ( 980) 0.0108601 (

( 251)-0.0110365 (

endSpecifier 

我不知道格式,每行多久重复infile中。

我需要得到阵列看起来像这样(在上面的示例):

a=[251, 268, 1267, 980, 251] 
b=-0.0110365, -0.0110365, 0.0108601,...] 

任何建议,如何解决这个问题?

回答

0

我会用

do line = 1,nlines !or just do and exit on end of file, it's up to you 
    lower = (line-1)*items_per_line + 1 
    upper = line*items_per_line 
    read (unit,fmt='(999(tr1,i5,tr1,f11))') (a(i),b(i),i=lower,upper) 
end do 

添加任何其他read(unit,*)跳过线,其中apropriate。

如果字段宽度确实是固定的,就像从您的示例中看到的那样。

+0

不幸的是,我不知道我期望有多少领域,所以我不知道“上”。该文件中的行是否有问题? – user1638145 2013-02-28 12:14:32

+0

对于换行符,您只需执行另一个相同的读取语句。 'lower'是数组索引,读取的是最后一个+1(开头为1),'upper'是最后一个读取的索引+行上的项目数。无论如何,您应该知道要读取的项目数,因为您的数组必须事先分配。 – 2013-02-28 12:52:33

+0

但我不知道itemp_per_line ... – user1638145 2013-02-28 13:14:59

0

在我oppinion,你有两种基本选择:

  • 您程序的Fortran链表,逐行读取文件中的行,解析线和您提取的元素添加到您的链接列表。阅读完成后,将链接列表转换为数组。我们在DFTB+中读取未知长度的用户数据时这样做,但这需要不少的编程。

  • 或者,您可以使用脚本语言从输入文件中提取数据并以更易于使用Fortran的格式进行存储。下面在Python的例子,但是你可以使用你选择的任何其他的脚本语言:

    from __future__ import print_function 
    import sys 
    import re 
    
    PAT1 = re.compile(r"\(\s*(?P<int>\d+)\)") 
    PAT2 = re.compile(r"\)\s*(?P<float>-?\d+\.\d+)\s*\(") 
    
    txt = sys.stdin.read() 
    ints = PAT1.findall(txt) 
    floats = PAT2.findall(txt) 
    
    print(len(ints)) 
    print(" ".join(ints)) 
    print(" ".join(floats)) 
    

    Store中的脚本convert.py并运行它想:

    python convert.py <mydata.dat> newdata.dat 
    

    ,我认为,你的数据存储在mydata.dat。新的文件newdata.dat
    会再看看这样的:

    5 
    251 168 1267 980 251 
    -0.0110365 -0.0110365 0.0108601 0.0108601 -0.0110365 
    

    这可以用Fortran语言阅读整在第一线, 轻松地分析分配你的整数 和浮点数组在它给出的大小,用两个读取 语句读入两个数组。