Search and Replace in a text.

paul at alanweberassociates.com paul at alanweberassociates.com
Mon Oct 4 21:25:52 CEST 2004


This kind of adaptive search/replace is a good option for pyparsing transformString.  Using this mode, one only needs to define the 
patterns to be matched, and in the case of substitution, return
the desired output string in the appropriate parseAction routine.

--------------------------
from pyparsing import *

# define relevant grammar strings
layerDefn = "Layer:" + restOfLine
attrDefn = "Attr:" + Word(nums)
searchPatterns = ( layerDefn | attrDefn )

# initialize layerData in case we get an Attr before a Layer
layerData = "<ERROR> no layer found"

# parse action to run when encounter "Layer"
def saveLayerData(strg,loc,tokens):
    global layerData
    layerData = tokens[1].strip()
layerDefn.setParseAction( saveLayerData )

# parse action to run when encounter "Attr"
def pasteLayerData(strg,loc,tokens):
    return "Attr: " + layerData    
attrDefn.setParseAction( pasteLayerData )

# test results
testdata = """
Layer: Tv-Frame
Flags: 0x0
Attr: 1
Focus Point: 0 0 0
Layer: Tv-pic
Flags: 0x2300
Attr: 1
Focus Point: 0 0 0
Layer: Tv-shell
Flags: 0x0
Attr: 1
Focus Point: 0 0 0
"""

print searchPatterns.transformString( testdata )
--------------------------
(output)
Layer: Tv-Frame
Flags: 0x0
Attr: Tv-Frame
Focus Point: 0 0 0
Layer: Tv-pic
Flags: 0x2300
Attr: Tv-pic
Focus Point: 0 0 0
Layer: Tv-shell
Flags: 0x0
Attr: Tv-shell
Focus Point: 0 0 0



-- Paul McGuire
Download pyparsing at http://pyparsing.sourceforge.net
 


More information about the Python-list mailing list