Python3.x读取带有头的文件(已标识标头之间的数据)

2024-10-04 11:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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.
  (...)
  n, x, y, z
*Element
  1, 1, 2, 3, 4
  2, 5, 6, 7, 8
  (...)
  n, a, b, c, d

从这个txt文件中,我需要创建一个名为“node”的矩阵,其中包含*node和*Element之间的信息,我的意思是,它必须有4列和n行,例如:

节点=数组([1,-0.600000024,1.20000005,0.],[2,-0.600000024,0.30000012,0.],[3,-0.480560571,0.1741862,0.],[4,-0.335430175,0.0791868418,0.],[n,x,y,z])

以及另一个名为“element”的矩阵,其中包含*element后面的行:

元素=数组([1,1,2,3,4],[2,5,6,7,8],[n,a,b,c,d])

实际上,我只需要“读取”文本文件并将此内容写入两个矩阵。但是,我必须将*节点下的信息与*下*元素下的信息分开。我必须有两个矩阵,一个有节点,另一个有元素。。。但我是Python新手,不知道如何用这种方式读取文本文件并生成这些矩阵。。。在

如有任何帮助/例子,我将不胜感激。谢谢!在


Tags: 文件txt信息node元素节点矩阵scipy
2条回答

用文件中的行创建一个列表,然后创建以indexif'*Node''*Element'开始和停止的子列表应该适合您:

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)

@EoinS有一个很好的解决方案,我想介绍一个替代方案,它在确定两个列表类型的开始和结束位置方面不那么动态,但是可以处理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 herehere读取csv的信息

相关问题 更多 >