2016-05-29 23 views
2

我正在使用Python 3.4,並且已經安裝了NunPy/SciPy。 我需要閱讀以下結構的文本文件:Python 3.x讀取頭文件(確定頭文件之間的數據)

*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行,例如:

node = array([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])

另一個叫做「元素」的矩陣,其中包含*元素之後的行:

元素=陣列([1,1,2,3,4],[2,5,6,7,8],[N,A,B,C,d])

事實上,我只需要「讀取」文本文件並將這些內容寫入兩個矩陣。但是,我必須將* Node下的信息與* Element下的信息分開。我必須有兩個矩陣,一個帶有節點,另一個帶有元素...但我是Python新手,不知道如何以這種方式讀取文本文件並生成這些矩陣...

I感謝任何幫助/例子。非常感謝!

+0

CSV的是整個文件? (節點/元素數據之前或之後沒有任何內容?)通常情況下,abaqus輸入文件中有更多關鍵字,但當然,如果這些關鍵字全部存在,它就會簡化。 – agentp

+0

是的,這是整個文件... 我的意思是,我必須編程自己的有限元素求解器(2D)在大學的一門課程。由於我是Abaqus用戶,因此我將讀取Abaqus格式的節點和元素,僅僅因爲這樣做,我就可以用更簡單的方式(使用某個預處理器)來準備模型。 我不確定是否應該使用Python或Matlab/Octave。我對這兩方面都只有非常基礎的知識,所以我必須反正學習,然後選擇了Python。 是更好的選擇嗎? = D – Paulo

回答

2

建立在你的文件中的行列表,然後創建子列表開始到index如果'*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) 
+0

嗨EoinS,謝謝你的回答。 我不明白以下用法: Node.append(map(float,i.split(','))) 爲什麼不使用:Node.append(i.split(',')) 如果我使用「地圖」,我該如何檢索值來對它們進行操作? 謝謝! Obs .:對不起,我剛剛開始使用Python ... – Paulo

+1

@Paulo使用map,第一個參數是一個函數,所以你可以通過定義一個函數來處理一個值,並將其作爲第一個參數傳入。這裏'float'用於將分割後的字符串轉換爲浮點數,而不是字符串。 –

0

@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

+0

謝謝喬希!我會嘗試的! – Paulo