2

I'm trying to remove multiple lines containing an obsoleted code fragment from various file with the help of python. I looked for some examples but could not really find what I was looking for. What I basically need is something that does in principle the following (contains non-python syntax):

def cleanCode(filepath):
"""Clean out the obsolete or superflous 'bar()' code."""
with open(filepath, 'r') as foo_file:
    string = foo_file[index_of("bar("):]
    depth = 0
    for char in string:
        if char == "(": depth += 1
        if char == ")": depth -= 1
        if depth == 0: last_index = current_char_position
with open(filepath,'w') as foo_file:
    mo_file.write(string)

The thing is that the construct I'm parsing for and want to replace could contain other nested statements that also need to be removed as part of the bar(...) removal.

Here is what a sample, to be cleaned, code snippet would look like:

annotation (
  foo1(k=3),
  bar(
    x=0.29,
    y=0,
    bar1(
    x=3, y=4),
    width=0.71,
    height=0.85),
  foo2(System(...))

I would think that someone might have solved something similar before :)

4

2 回答 2

2

try this :

clo=0
def remov(bar):
   global clo
   open_tag=strs.find('(',bar) # search for a '(' open tag
   close_tag=strs.find(')',bar)# search for a ')' close tag
   if open_tag > close_tag:
      clo=strs.find(')',close_tag+1)
   elif open_tag < close_tag and open_tag!=-1:
      remov(close_tag)



f=open('small.in')
strs="".join(f.readlines())
bar=strs.find('bar(')
remov(bar+4)
new_strs=strs[0:bar]+strs[clo+2:]
print(new_strs)
f.close()   

output:

annotation (
  foo1(k=3),
  foo2(System(...))
于 2012-04-25T16:02:38.320 回答
2

Pyparsing has some built-ins for matching nested parenthetical text - in your case, you aren't really trying to extract the content of the parens, you just want the text between the outermost '(' and ')'.

from pyparsing import White, Keyword, nestedExpr, lineEnd, Suppress

insource = """
annotation (
  foo1(k=3),
  bar(
    x=0.29,
    y=0,
    bar1(
    x=3, y=4),
    width=0.71,
    height=0.85),
  foo2(System(...))
"""

barRef = White(' \t') + Keyword('bar') + nestedExpr() + ',' + lineEnd

out = Suppress(barRef).transformString(insource)
print out

Prints

annotation (
  foo1(k=3),
  foo2(System(...))

EDIT: parse action to not strip bar() calls ending with '85':

barRef = White(' \t') + Keyword('bar') + nestedExpr()('barargs') + ','
def skipEndingIn85(tokens):
    if tokens.barargs[0][-1].endswith('85'):
        raise ParseException('ends with 85, skipping...')
barRef.setParseAction(skipEndingIn85)
于 2012-04-25T20:11:21.767 回答