以纯文本形式写入和读取 numpy 对象 [英] Writing and Reading numpy objects an plain text
问题描述
在 Python 中,我想以纯文本格式存储 numpy 数组、矩阵和其他可能的对象.
In Python, I would like to store numpy arrays, matrices and possibly later other objects in plain text format.
我的想法是使用 ConfigParser 并定义解析器 array2string
、matrix2string
、string2array
和 string2matrix
(有numpy.array2string
和 matrix2string
可以基于此实现,但我找不到相反的函数).然后写成这样:
My idea was to use ConfigParser and define parser array2string
, matrix2string
, string2array
and string2matrix
(there is numpy.array2string
and matrix2string
could be implemented based on that, but I couldn't find functions for the reverse). Then writing looks like:
config.set('calibration', 'center', array2string(center))
config.set('calibration', 'trans_matrix', matrix2string(trans_matrix))
并阅读如下:
center = string2array(config.get('calibration', 'center'))
trans_matrix = string2matrix(config.get('calibration', 'trans_matrix'))
编写和读取 numpy 对象的最佳方法是什么?
What is the best way to write and read the numpy objects?
推荐答案
这篇文章中的答案提供了一个很好的功能:
Answer in this post gives a nice function which works well:
import configparser
import re
import ast
import numpy as np
def str2array(s):
# Remove space after [
s=re.sub('\[ +', '[', s.strip())
# Replace commas and spaces
s=re.sub('[,\s]+', ', ', s)
return np.array(ast.literal_eval(s))
config = configparser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")
var_d=config.get("myvars", "var_d")
var_e=config.get("myvars", "var_e")
q=str2array(var_d)
r=str2array(var_e)
config.ini 文件在哪里:
Where the config.ini file is:
# Variable tests
#
#
[myvars]
var_a='home'
var_b='car'
var_c=15.5
var_d=[2.1 3.4 4.6]
var_e=[[ 1.1 2.2 2.233]
[ 1.00000000e+02 1.17809494e+03 4.9410e+02]
[ 2.00000000e+04 1.20e+01 1.2323e+04]]
这篇关于以纯文本形式写入和读取 numpy 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!