2017-06-03 102 views
-1

我有一個由mathematica生成的文本文件。我想將文本文件python轉換爲可讀。主要問題是文件將數組存儲爲大括號(「{......}」)。另一個問題是,數學使用I作爲python使用j的虛數。解決辦法是什麼?複數交換閱讀Mathematica生成的文本文件

+5

再次問同樣的問題。 ? https://stackoverflow.com/q/44173958/1004168。你應該清楚地解釋爲什麼你想要使用那種奧術格式,而不是十幾個其他人更容易處理。 – agentp

+0

@agentp說什麼。但是也許你可以用'CForm'加上一些支持的定義來得到你想要的,例如'def List(* x):return list(x)'。 – Alan

+2

[數據從Mathematica導入到Python]可能的重複(https://stackoverflow.com/questions/44173958/data-from-mathematica-import-to-python) –

回答

0

例如:

數學:

Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}] 

蟒:

import csv 
    reader=csv.reader(open('cmplx.csv','r')) 
    complexarray=[complex(item.replace('*I','j')) 
     for row in reader for item in row] 

這適合真正爲少量數據。對於大型陣列,我會拆分實部和虛部以分開陣列,使用此處顯示的二進制交換https://stackoverflow.com/a/44184067/1004168並重新組裝以使其與numpy複雜。

數學:

m = Table[RandomComplex[], {3}, {3}] 
f = OpenWrite["test.bin", BinaryFormat -> True]; 
BinaryWrite[f, ArrayDepth[m], "Integer32"]; 
BinaryWrite[f, Dimensions[m], "Integer32"]; 
BinaryWrite[f, Re[m], "Real64"]; 
BinaryWrite[f, Im[m], "Real64"]; 
Close[f] 

蟒蛇:

import numpy as np 
with open('test.bin','rb') as f: 
depth=np.fromfile(f,dtype=np.dtype('int32'),count=1) 
dims=np.fromfile(f,dtype=np.dtype('int32'),count=depth) 
count=reduce(lambda x,y:x*y,dims) 
complexarray=np.reshape(np.fromfile(f,dtype=np.dtype('float64'), 
    count=count),dims) 
complexarray=complexarray+ 
    1j*np.reshape(np.fromfile(f,dtype=np.dtype('float64'), 
    count=count),dims)