选择行堆栈python

时间:2011-02-11 15:51:51

标签: python

我写了这段代码:

import os
import re
import string
##
Path = 'C:/RESULT/BATCH/'
##
Nfile = 'Skin_Refined_v05'
f=open(Path + Nfile + '.inp')
n=open(Path + 'newfile.inp', 'w')
for lines, text in enumerate(f):
   found = text.find('*SURFACE')
   while found > -1:
    print found, lines, text
    found = text.find('*SURFACE', found + 1)
    n.write(text)
##
f.close()
n.close()

这就是* .inp的样子(通常约为30Mb)

*SURFACE, NAME = BOTTOM, TYPE = ELEMENT
  40012646, S2   
  40012647, S2   
  40012648, S2   
  40012649, S2   
  40012650, S2   
  40012651, S2   
*SURFACE, NAME = ALL_INT_TIE_1, TYPE = ELEMENT
  40243687, S3   
  40243703, S3   
  40243719, S3   
  40243735, S3   
  40243751, S3   
  40243767, S3   
**
*TIE, NAME = INTERNAL_TIE, POSITION TOLERANCE = 1.0     , ADJUST=NO
SLAVE,MASTER
*TIE, NAME = SKN_REF_1
ALL_INT_FRONT, ALL_EXT_FRONT
*TIE, NAME = SKIN_LAT
ALL_INT_LAT, ALL_EXT_LAT
*TIE, NAME = SKIN_TIE_1
ALL_INT_TIE_1, ALL_INT_TIE_2
**
*SURFACE , NAME = TOP, COMBINE = UNION
TOP_1
TOP_2
**HM_UNSUPPORTED_CARDS
*END PART
*****

他做的很清楚。我想要实现的是获得以数字开头的* SURFACE之间的所有线条,然后我将不得不以不同的方式安排,但我会稍后担心。

我重写了代码cos我无法按照建议工作,现在它正在创建我需要它们的块,但是我如何在每个块上工作?

我需要分离所有元素(数字后跟S1,S2等)并为每个块创建分组,按S1,S2等排序,最终结果应如下所示

* ELSET,ELSET = TOP_S1
40221320,40221306,40221305,40221304,40221290,40221289,40221288,40221274,
40221273,40221272,40221258,40221257,40221256,40221242,40221241,40221240,
*表面,名称=顶部,类型=元素
TOP_S1,S1

import os 
import re
import string

## 
Path = 'C:/RESULT/BATCH/' 
## 
Nfile = 'Skin_Refined_v05' 
f=open(Path + Nfile + '.inp') 
n=open(Path + 'newfile.inp', 'w') 
in_surface_block = False;
for line_num, text in enumerate(f): 
    found = text.find('*SURFACE') 
    if found > -1:
        in_surface_block=True;
        print found, line_num, text         
        surface_lines = []
        continue
    if in_surface_block:
        m = re.match('\s*\d+\,\s*\w\d+',text)
        if m:
            mtext = m.group(0)
##            p=surface_lines.append(text)
            print mtext
##            ntext = surface_lines.append(m.group(0))
##            n.write(ntext)

## 
f.close() 
n.close()

我希望很清楚

1 个答案:

答案 0 :(得分:1)

我认为这会做你想做的事情:

import os 
import re 

## 
Path = 'C:/RESULT/BATCH/' 
## 
Nfile = 'Skin_Refined_v05' 
f=open(Path + Nfile + '.inp') 
n=open(Path + 'newfile.inp', 'w') 
in_surface_block = False;
for line_num, text in enumerate(f): 
    found = text.find('*SURFACE') 
    if found > -1:
        in_surface_block=True;
        print found, line_num, text         
        surface_lines = []
        continue

    if in_surface_block:
        if re.match('\s*\d+', text):
            surface_lines.append(text)
        else:
            in_surface_block = False
            // do surface lines work here:
            // surface_lines is a list with all the lines in a surface block 
            // that start with a number
            ...
## 
f.close() 
n.close() 

编辑:修正了逻辑错误