python读取mat数据是字典形式如何转化为矩阵_mat2json, python读取mat成字典, 保存json...

该Python脚本通过`loadmat`函数读取MATLAB的.mat文件,将字典内容转化为JSON。它首先使用`scipy.io`加载MAT文件,然后检查并转换所有MAT对象为字典。最后,可以将结果字典保存为JSON文件。
摘要由CSDN通过智能技术生成

python程序, 实现matlab的.mat格式转化为dict / json .python

第一个参数mat_path表明须要转化的mat路径;

第二个参数, 若是须要把字典序列化成json, 添加这一参数, 表明json存放位置;

返回值: 转化好的字典

import os

import json

import scipy.io as spio

import pandas as pd

def loadmat(filename):

'''

this function should be called instead of direct spio.loadmat

as it cures the problem of not properly recovering python dictionaries

from mat files. It calls the function check keys to cure all entries

which are still mat-objects

'''

data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)

return _check_keys(data)

def _check_keys(dict):

'''

checks if entries in dictionary are mat-objects. If yes

todict is called to change them to nested dictionaries

'''

for key in dict:

if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):

dict[key] = _todict(dict[key])

return dict

def _todict(matobj):

'''

A recursive function which constructs from matobjects nested dictionaries

'''

dict = {}

for strg in matobj._fieldnames:

elem = matobj.__dict__[strg]

if isinstance(elem, spio.matlab.mio5_params.mat_struct):

dict[strg] = _todict(elem)

else:

dict[strg] = elem

return dict

def mat2json(mat_path=None, filepath = None):

"""

Converts .mat file to .json and writes new file

Parameters

----------

mat_path: Str

path/filename .mat存放路径

filepath: Str

若是须要保存成json, 添加这一路径. 不然不保存

Returns

返回转化的字典

-------

None

Examples

--------

>>> mat2json(blah blah)

"""

matlabFile = loadmat(mat_path)

#pop all those dumb fields that don't let you jsonize file

matlabFile.pop('__header__')

matlabFile.pop('__version__')

matlabFile.pop('__globals__')

#jsonize the file - orientation is 'index'

matlabFile = pd.Series(matlabFile).to_json()

if filepath:

json_path = os.path.splitext(os.path.split(mat_path)[1])[0] + '.json'

with open(json_path, 'w') as f:

f.write(matlabFile)

return matlabFile

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值