Python3.x读取带有标题的文件(已识别标题之间的数据)
我正在使用Python3.4,并且已经安装了NunPy/SciPy。 我需要读取具有以下结构的文本文件:Python3.x读取带有标题的文件(已识别标题之间的数据),python,numpy,matrix,text,abaqus,Python,Numpy,Matrix,Text,Abaqus,我正在使用Python3.4,并且已经安装了NunPy/SciPy。 我需要读取具有以下结构的文本文件: *Node 1, -0.600000024, 1.20000005, 0. 2, -0.600000024, 0.300000012, 0. 3, -0.480560571, 0.1741862, 0. 4, -0.335430175, 0.0791868418, 0. (...)
*Node
1, -0.600000024, 1.20000005, 0.
2, -0.600000024, 0.300000012, 0.
3, -0.480560571, 0.1741862, 0.
4, -0.335430175, 0.0791868418, 0.
(...)
n, x, y, z
*Element
1, 1, 2, 3, 4
2, 5, 6, 7, 8
(...)
n, a, b, c, d
从这个txt文件中,我需要创建一个名为“节点”的矩阵,其中包含*节点和*元素之间的信息,我的意思是,它必须有4列和n行,例如:
节点=数组([1,-0.60000024,1.2000005,0.],[2,-0.60000024,0.30000012,0.],[3,-0.480560571,0.1741862,0.],[4,-0.335430175,0.0791868418,0.],[n,x,y,z])
和另一个称为“元素”的矩阵,其中包含*元素后面的行:
元素=数组([1,1,2,3,4],[2,5,6,7,8],[n,a,b,c,d])
事实上,我只需要“读取”文本文件并将这些内容写入两个矩阵。但是,我必须将*节点下的信息与*元素下的信息分开。我必须有两个矩阵,一个有节点,另一个有元素。。。但我是Python新手,不知道如何以这种方式读取文本文件并生成这些矩阵
我将感谢任何帮助/示例。非常感谢 使用文件中的行创建一个列表,然后在
索引处开始和停止创建子列表,如果'*节点'
和'*元素'
,则应该适合您:
r=[]
s = open('File.txt')
For line in s:
r.append(line.strip('\n'))
Node=[]
Element=[]
For i in r[r.index('*Node')+1:r.index('*Element')]:
Node.append(map(float,i.split(',')))
For j in r[r.index('*Element')+1:]:
Element.append(map(int, j.split(','))
Node=np.array(Node)
Element=np.array(Element)
有一个很好的解决方案,我想提供一个在计算两个列表类型的开始和结束位置方面不太动态的替代方案,但将处理CSV格式的各种边缘情况,并具有以下列名:
import numpy as np
node_rows = 75 #number of lines in the node section
interstitial_rows = 5 #number of lines between the last node record and the first element
element_rows = 1000 #the number of element rows
nodes = np.genfromtxt(
'sample.csv', # file name
skip_header=1, # lines to skip at the top, i assume there is a header
skip_footer=(interstitial_rows + 1 + element_rows), # lines to skip at the bottom, add one for the column name row at the end
delimiter=',', # column delimiter
names=['n', 'x', 'y', 'z'])
elements = np.genfromtxt(
'sample.csv', # file name
skip_header=(1 + node_rows + interstitial_rows), # lines to skip at the top, i assume there is a header
skip_footer=(1), # one for the column name row at the end
delimiter=',', # column delimiter
names=['n', 'a', 'b', 'c', 'd'])
请注意,我没有测试这段代码,我一直在使用类似的代码,但可能有语法错误或遗漏了什么
您可以找到有关如何使用numpy和Hi-EoinS阅读CSV的更多信息,谢谢您的回答。我不明白:Node.append(map(float,I.split('),'))的用法为什么不只使用:Node.append(I.split('),'))如果我使用“map”,我如何检索要在其上操作的值?谢谢Obs.:对不起,我只是从Python开始…@Paulo with map,第一个参数是一个函数,因此您可以通过定义一个处理一个值的函数并将其作为第一个参数传入来操作这些值。这里的float
用于将split给出的字符串转换为浮点数,而不是字符串。谢谢Josh!我试试看!这是全部文件吗?(在节点/元素数据之前或之后没有任何内容?)通常abaqus输入文件中有更多的关键字,但如果仅此而已,当然它可以简化事情。是的,这就是整个文件。。。我的意思是,我必须为大学的课程编写自己的有限元解算器(2D)。由于我是Abaqus用户,我将以Abaqus格式读取节点和元素,因为这样做,我可以以更简单的方式准备模型(使用一些预处理器)。我怀疑我是否应该使用Python或Matlab/Octave。我在这两方面都只有非常基本的知识,所以无论如何我都要学习,然后我选择了Python。这是更好的选择吗=D