简体   繁体   English

使用python从文本文件导入矩阵

[英]Import matrix from text file using python

I have two text files that have matrices written in them(not numpy matrices, so its a list of lists). 我有两个文本文件,其中写有矩阵(不是numpy矩阵,因此是列表列表)。 These matrices are written in string format, so the text file looks like this : [[1,2,3],[3,4,5],[6,7,8]],[[3,3,3],[5,6,7],..... 这些矩阵以字符串格式编写,因此文本文件如下所示:[[1,2,3],[3,4,5],[6,7,8]],[[3,3,3] ,[5,6,7],.....

I want to read this matrix back from the text file using python. 我想使用python从文本文件中读回此矩阵。 I can't read using numpy as it gives ValueError: could not convert string to float 我无法使用numpy读取,因为它给出了ValueError: could not convert string to float

Is there anyway to do this? 反正有这样做吗? Would it be easier if I just wrote the matrix as a numpy matrix in the first place(I need to change code of a previous program for that, and was just wondering if there was a python way of loading matrices when it was stored as a string in a text file)? 如果我首先将矩阵编写为numpy矩阵会更容易(我需要为此更改以前程序的代码,并且只是想知道在将python存储为a时是否存在python加载矩阵的方式)文本文件中的字符串)?

You could make use of the ast module: 您可以使用ast模块:

import ast

strArray =  "[[1,2,3],[3,4,5],[6,7,8]]"

# evaluates the array in string format and converts it to a python array object
array = ast.literal_eval(strArray)

note: For multiple nested arrays like you have, literal_eval will most likely convert the string into a tuple with nested arrays as elements. 注意:对于像您一样的多个嵌套数组, literal_eval最有可能将字符串转换为以嵌套数组为元素的元组。 Just keep that in mind as you use this module. 使用此模块时,请记住这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM