将矩阵式字符串转换为矩阵

时间:2017-02-13 22:35:13

标签: python python-3.x numpy matrix text

我想将.txt文件中的字符串转换为可在我的代码中使用的实际矩阵。 .txt文件如下所示:

Version:1

Matrix1
[ 0.83568616  2.15352694 -4.4027591  -1.74058247 -0.42605484 -0.21766954]
[-1.0363443  -1.07584464  0.67931046  1.82348912  1.71141435 -0.40177167]
[-0.49192281  0.83897739 -0.97685038  1.3442258   1.91058796 -0.46493662]
[ 0.42825634 -0.58257726  2.0370751  -1.11937523 -3.81475336  2.66557629]

我尝试过不同的方式,但这就是我现在所拥有的:

f = open("C:/Users/Username/Desktop/Output_data/output_data1.txt", "r")
string1 = [x.strip() for x in f.readlines()]
string1 = string1[3:7]
Matrix1 = np.array(string1)
for elem in Matrix1:
    elem = float(elem)

这不起作用,因为Matrix1的(elem)是一个字符串(包括括号)。

有没有一种简单的方法可以将其转换为我可以使用的矩阵?

2 个答案:

答案 0 :(得分:0)

<form action="{% url 'password_change_done' %}" method="post"> {% csrf_token %} {% bootstrap_form form layout="inline" form_group_class="form-group col-md-6" %} <div class="clearfix"></div> {% buttons %} <button type="submit" name="save" class="btn btn-primary">{% bootstrap_icon "plus" %} {% trans 'save' %}</button> {% endbuttons %} </form> 接受字符串作为参数但是特殊格式,即没有括号和换行符应该是分号,因此如果删除方括号并用numpy.matrix替换换行符,则可以使用;阅读它们:

numpy.matrix

对于您的情况,您可以尝试逐行加载数据(可能有更好的方法)并将它们添加到空矩阵中:

s = """[ 0.83568616  2.15352694 -4.4027591  -1.74058247 -0.42605484 -0.21766954]
[-1.0363443  -1.07584464  0.67931046  1.82348912  1.71141435 -0.40177167]
[-0.49192281  0.83897739 -0.97685038  1.3442258   1.91058796 -0.46493662]
[ 0.42825634 -0.58257726  2.0370751  -1.11937523 -3.81475336  2.66557629]"""
​
import numpy as np    ​
mat = np.matrix(s.replace('[', '').replace(']', '').replace('\n', ';'))
​
mat
# matrix([[ 0.83568616,  2.15352694, -4.4027591 , -1.74058247, -0.42605484, -0.21766954],
#         [-1.0363443 , -1.07584464,  0.67931046,  1.82348912,  1.71141435, -0.40177167],
#         [-0.49192281,  0.83897739, -0.97685038,  1.3442258 ,  1.91058796, -0.46493662],
#         [ 0.42825634, -0.58257726,  2.0370751 , -1.11937523, -3.81475336, 2.66557629]])

答案 1 :(得分:0)

代码的开头......

f = open("C:/Users/Username/Desktop/Output_data/output_data1.txt", "r")
string1 = [x.strip() for x in f.readlines()]
string1 = string1[3:7]

到目前为止一直很好,现在我们想要做一些不同的事情,使用你的风格,可以像这样写出

# strip the [] brackets
string1 = [x[1:-1] for x in string1]

# data is a list of lists of floating point numbers
data = [[float(f) for f in x.split()] for x in string1]

# a list of lists is almost an array, the final step is
Matrix1 = np.array(data)

简而言之

mat = np.array([[float(x) for x in l.strip()[1:-1].split()] for l in f.readlines()[3:7]])
相关问题