• mat2json, python读取mat成字典, 保存json


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

    • 第一个参数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
    

    更改自mat2json

  • 相关阅读:
    Java.Util.List(List接口)
    在VMware安装Centos7
    java中原生的发送http请求(无任何的jar包导入)
    二叉树算法的收集
    javascript将list转换成树状结构
    CSS实现鼠标悬浮无限向下级展示的简单代码
    Jquery的框架解析
    mybaits插入时的一些总结
    苹果手机在有滚动条的情况下,滑动不顺畅的原因
    tomcat下jndi的三种配置方式
  • 原文地址:https://www.cnblogs.com/geoffreyone/p/11077327.html
Copyright © 2020-2023  润新知