Search and replace in a text.

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Oct 5 14:29:42 CEST 2004


On 10/1, Dong Ge wrote:
>I'm a new beginner of Python. I want to convet
> "Text 1" to "Text 2"
> below. How to do it?
>
>__
>Dong Ge
>2004.10.01
>
>Text 1:
>...
>Layer: Tv-Frame
>Flags: 0x0
>Attr: 1  (replace "1" with contents of previous
>          "Layer" line - "Tv-Frame")
<snip>

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"

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

# define 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