简体   繁体   English

如何从 txt 文件创建矩阵/数组?

[英]How can I create a matrix/array from a txt file?

kinetic_e = open('t.dat.txt', 'r')
print kinetic_e

p_word = re.compile(r'\S+')
for line in kinetic_e:
    m = re.findall(p_word, line)
    print m

The file in question: http://sirius.chem.vt.edu/~crawdad/programming/project3/h2o_sto3g/t.dat ...the first 2 columns have numbers 1-7 which I want for the dimensions of the matrix.有问题的文件: http : //sirius.chem.vt.edu/~crawdad/programming/project3/h2o_sto3g/t.dat ...前两列有数字 1-7,我想要矩阵的维度. Column 1 and 2 specify the row/column number for the numbers in the 3rd column.(Example: first row is row1,col1 then row2,col1 etc.)第 1 列和第 2 列指定第 3 列中数字的行/列号。(例如:第一行是 row1,col1 然后 row2,col1 等)

My question: Am I on the right path to solving this and can I use regex to get through this problem?我的问题:我是否走在正确的道路上来解决这个问题,我可以使用正则表达式来解决这个问题吗? I'm having trouble finding sources to do this to create a 7x7 matrix with all the data我很难找到来源来创建一个包含所有数据的 7x7 矩阵

No, wrong path.不,走错路了。 No need for regex here.这里不需要正则表达式。 Initialize a 7x7 2D-array.初始化一个 7x7 二维数组。 Loop throug the lines, split them, extract the i,j indexes from the first two columns and set the value of the 2d array with the third field:循环遍历这些行,拆分它们,从前两列中提取 i,j 索引,并使用第三个字段设置 2d 数组的值:

matrix = [[0 for i in range(7)] for j in range(7)]
with open('t.dat.txt', 'r') as source:
    for line in source:
        i, j, value = line.split()
        i, j = int(i), int(j)
        matrix[i - 1][j - 1] = float(value)

You can do this without regular expressions.您可以在没有正则表达式的情况下执行此操作。 The data is already in a easily manipulated state as it is.数据已经处于易于操作的状态。 You'll want to loop for each line in the file and just use the split method by the looks of it.您将希望对文件中的每一行进行循环,并根据它的外观使用 split 方法。

As far as mapping the rows and columns, you could stick a Python list inside of another (making sure the lists are of the correct sizes for list assignments) or doing the same thing with dictionaries so you don't need to worry about the sizes.至于映射行和列,您可以将 Python 列表粘贴到另一个列表中(确保列表具有正确的列表分配大小)或对字典执行相同的操作,因此您无需担心大小. Whichever one you choose for this, you can just do the assignment per row in your loop to get all the lines.无论您为此选择哪一个,您都可以在循环中对每一行进行分配以获取所有行。

Edit编辑

Seems like Bernhard above was a little quicker than me on the reply.似乎上面的伯恩哈德在回复上比我快一点。

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

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