2013-06-27 45 views
1

我有這段代碼讀取Fortran未格式化的數據文件並將ascii輸出寫入 一個新文件output.dat。我想將這個output.dat文件讀入一個numpy數組。但是,fromfile實用程序會讀取奇怪的值,我認爲這是由於「dtype」不匹配造成的。我嘗試了所有可能的dtypes,但我仍然沒有得到正確的值。有人能指導我在這裏應該做什麼。在不知道數據大小的情況下從文件讀取浮點數作爲numpy數組

我的代碼來讀取FORTRAN未格式化和寫入ASCII,並且也可以參考ASCII文件到一個 陣列numpy的:

# Code unformatierten Fortran-Dateien mit Python lesen 

import numpy as np 
from struct import * 
import fortranfile as fofi 
from array import array 

f = fofi.FortranFile('extract.bin',endian='>',header_prec='i') 
x = f.readInts() 
xx = f.readReals('f') 

print x 
print 'Die Lange von x ist',len(x) 
print 'Dies ist' 
print xx[0:20] 
print 'Die Lange ist',len(xx) 
dd = list(xx) 
d = list(x) 


df=len(xx)/8 
print 'Der Wert ist',df 
g = fofi.FortranFile('output.dat',mode='w') 
g.writeRecord(str(d)) 
g.write('\n') 
g.writeRecord(str(dd)) 
g.close() 

filename = open('output.dat','rb') 
field = np.fromfile(filename,dtype=np.float64) 
filename.close() 
print field 

的Python讀取無格式Fortran和寫入到輸出文件中。該文件包含一些我不知道如何刪除的DLE,FS和NUL字符。 'YS'字符也是轉換的一部分。

[1, 167, 133, 6] 
YS [0.0, 4.3025989e-07, 1.5446712e-06, 3.1393029e-06, 5.0430463e-06, 7.1382601e-06, `9.301104e-06, 1.1476222e-05, 1.3561337e-05, 1.5552534e-05, 1.7355138e-05, 1.9008177e-05, `2.0416919e-05, 2.1655113e-05, 2.2624969e-05, 2.3426954e-05, 2.3961067e-05, 2.4346635e-05, 2.4482841e-05, 2.45e-05, 2.43e-05, 2.4020905e-05, 2.3559202e-05, 2.3056287e-05, 2.2411346e-05, 2.1758024e-05, 2.1005515e-05, 2.0265579e-05, 1.9453466e-05, 1.8686056e-05, 1.7860904e-05, 1.7103739e-05, 1.6299076e-05, 1.5573576e-05, 1.4809892e-05, 1.4126301e-05, 1.3412908e-05, 1.2775883e-05, 1.2116507e-05, 1.1522323e-05, 1.0915101e-05, 1.0356307e-05, 

目前,我的輸出是

[ 1 167 133 6] 
Die Lange von x ist 4 // The length of x is 
Dies ist // This is (The actual value) 
[ 0.00000000e+00 4.30259888e-07 1.54467125e-06 3.13930286e-06 
    5.04304626e-06 7.13826012e-06 9.30110400e-06 1.14762224e-05 
    1.35613373e-05 1.55525340e-05 1.73551380e-05 1.90081773e-05 
    2.04169191e-05 2.16551125e-05 2.26249686e-05 2.34269537e-05 
    2.39610672e-05 2.43466347e-05 2.44828407e-05 2.45e-05] 
Die Lange ist 133266 // The length is 
Der Wert ist 16658 // The value (after reading with numpy) is 
[ 4.66529177e-062 3.47245665e-313 3.28870023e-086 ..., 
    1.05249949e-153 1.69339332e-052 3.30673243e+093] 

numpy的閱讀之後並不像以前一樣,該數組的值。我如何解決這個問題 並將所有這些值讀入我選擇的numpy數組中?另外,如果你有更好的閱讀fortran未格式化文件的建議,請評論。

+0

你能展示一個需要閱讀的示例文件嗎? –

+0

示例文件是中間的一長串數字......以[1,167,133,6]開頭,然後是YS後面的那個.. – atmaere

+0

和方括號等等?那麼文件的精確格式是什麼? –

回答

1

如果您在Linux上,請使用翻譯工具tr 刪除除0-9 + - 之外的所有字符。如果您需要NaN空白標籤換行符:

tr -C -d '0-9 + \- . ef EF inf NaN \t\n' <in> out # delete non-numbers 

(不太清楚如果這就是您想要做的)。

此外,請使用fromfile(file, sep=' ')
讀取一個文本文件,其中的數字用空白(空格,製表符,換行符)分隔;
默認sep=''用於讀取二進制文件。

Viel Glueck

相關問題