python调用mathematica代码,Mathematica中的数据导入到Python

I have a text file containing 3 dimensional array(100X100X100) obtained from Mathematica. The data are stored with commas and curly braces.I want to use this text file to analyse and plot the data using Python. How can I import the data in Python? I am currently using Python 2.7 version. What may be the format to store the data in matematica in order to use it in Python?

解决方案

since it pains me to see folks storing so much data in ascii, here is a way to do a binary exchange:

mathematica:

data = RandomReal[{-1, 1}, {3, 4, 5}]

f = OpenWrite["test.bin", BinaryFormat -> True];

BinaryWrite[f, ArrayDepth[data], "Integer32"];

BinaryWrite[f, Dimensions[data], "Integer32"];

BinaryWrite[f, data, "Real64"];

Close[f]

python:

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)

data =np.reshape(np.fromfile(f,dtype=np.dtype('float64'),

count=reduce(lambda x,y:x*y,dims)),dims)

note you can have endian-ness issues if you read/write on different hardware.

( easily handled though )

Edit: for completeness a text exchange using native mathematica format looks like this:

mathematica:

m = RandomReal[{-1, 1}, {8, 8}]

m >> out.m

python:

with open('out.m','r') as f: text=f.read()

for rep in (('{','['),('}',']')):text=text.replace(rep[0],rep[1])

array=eval(text)

with a couple notes of caution, first eval should not be used on untrused input, secondly this will break if any values use scientific notation, or obviously any mathematica symbolic content. Finally it will undoubtedly be painfully slow for large input. I would seriously only use this if you are stuck with a mathematica file and can not use mathematica to put it to a better format.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值