Python 读取生成的文本文件
我有一个mathematica生成的文本文件。我想将文本文件转换为python可读的文件。主要问题是该文件存储了带花括号(“{……}”)的数组。另一个问题是mathematica使用I作为虚数,而python使用j。解决办法是什么 复数交换示例: mathematica:Python 读取生成的文本文件,python,text,wolfram-mathematica,Python,Text,Wolfram Mathematica,我有一个mathematica生成的文本文件。我想将文本文件转换为python可读的文件。主要问题是该文件存储了带花括号(“{……}”)的数组。另一个问题是mathematica使用I作为虚数,而python使用j。解决办法是什么 复数交换示例: mathematica: Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}] m = Table[RandomComplex[], {3}, {3}] f = OpenWrite["test.
Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}]
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]
python:
import csv
reader=csv.reader(open('cmplx.csv','r'))
complexarray=[complex(item.replace('*I','j'))
for row in reader for item in row]
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)
这确实适用于少量数据。对于大型数组,我将实数部分和虚数部分分开,以分离数组,使用此处所示的二进制交换,并重新组合成numpy
mathematica:
Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}]
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]
python:
import csv
reader=csv.reader(open('cmplx.csv','r'))
complexarray=[complex(item.replace('*I','j'))
for row in reader for item in row]
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)
再次问同样的问题。你应该清楚地解释为什么你想使用这种神秘的格式,而不是字面上的十几种更容易处理的格式。但是,也许您可以通过
CForm
以及一些支持定义来获得所需的内容,例如,def List(*x):return List(x)
。可能是