replace words
Paul McGuire
ptmcg at austin.rr.com
Wed Oct 26 15:26:39 EDT 2005
More information about the Python-list mailing list
Wed Oct 26 15:26:39 EDT 2005
- Previous message (by thread): replace words
- Next message (by thread): replace words
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
hagai26 at gmail.com wrote: > What is the way for replacing in a string from . to . the sentence? > for example: > "been .taken. it may be .left. there, > even if the .live coals were not. cleared" > I want to do this-> replace(\.(.*)\.,\.start (1) end\.) > result: > "been .start taken end. it may be .start left end. there, > even if the .start live coals were not end. cleared" Here is a pyparsing version. Yes, it is more verbose, and, being pure Python, is not as fast as regexp. But the syntax is very easy to follow and maintain, and the parse actions can add quite a bit of additional logic during the parsing process (for example, rejecting dot pairs that span line breaks). -- Paul from pyparsing import Literal,SkipTo data = """been .taken. it may be .left. there, even if the .live coals were not. cleared""" DOT = Literal(".") # expression to match, comparable to regexp r"\.(.*?)\." dottedText = DOT + SkipTo(DOT).setResultsName("body") + DOT # action to run when match is found - return modified text def enhanceDots( st, loc, tokens): return ".start " + tokens.body + " end." dottedText.setParseAction( enhanceDots ) # transform the string print dottedText.transformString( data ) Gives: been .start taken end. it may be .start left end. there, even if the .start live coals were not end. cleared
- Previous message (by thread): replace words
- Next message (by thread): replace words
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list