阅读Mathematica生成的文本文件

时间:2017-06-03 10:50:09

标签: python text wolfram-mathematica

我有一个由mathematica生成的文本文件。我想转换文本文件python可读。主要问题是该文件存储带有大括号的数组(" {......}")。另一个问题是mathematica使用I作为虚数,而python使用j。解决办法是什么?

1 个答案:

答案 0 :(得分: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)