multiple replaces

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Harald Armin  Massa

    #1

    multiple replaces

    again, and again ... another try of templating

    txt="""
    <html>
    <body>
    <p>whatever</p>
    <!--tree-->
    <p>the machine with bing</p>
    <!--house-->
    <p>10% of boo is foo</p>
    </html>"""

    h1=txt.replace( "%","%%")
    h2=h1.replace(" <!--tree-->","%(tree)s" )
    h3=h2.replace(" <!--house-->","%(house)s ")

    house="somethin g awfull"
    tree="something beautifull"
    print h3 % locals()


    --> the <!--something--> approach allows it for me, that I can write
    real HTML which looks fair. The replacing-chain takes care of % signs
    within the file, and also makes a template for string replaces

    BUT... it looks terribly inefficient to me. There are 3 strings which
    are only there to be garbage collected. I am looking for a speedy way
    of
    "go through the text, and if you find sth. that is in REPLACEMENT,
    replace it with it"

    sth. like
    rpdict={"<!--tree-->":"%(tree)s"," <!--house-->":"%(house)s", "%","%%"}

    for key, value in rpdict.iteritem s():
    h1=h1.replace(k ey, value)

    but ... without the garbage, in one command.

    I guess there are very, very, very wise solution for this problem, but
    I do not know of them.

    Who knows and tells me?

    Harald

  • Fredrik Lundh

    #2
    Re: multiple replaces

    Harald Armin Massa wrote:
    [color=blue]
    > sth. like
    > rpdict={"<!--tree-->":"%(tree)s"," <!--house-->":"%(house)s", "%","%%"}
    >
    > for key, value in rpdict.iteritem s():
    > h1=h1.replace(k ey, value)
    >
    > but ... without the garbage, in one command.
    >
    > I guess there are very, very, very wise solution for this problem, but
    > I do not know of them.[/color]



    </F>



    Comment

    • D H

      #3
      Re: multiple replaces

      You can use python's re.sub function. But also look into full fledged
      template engines like Cheetah.

      import re

      txt="""
      <html>
      <body>
      <p>whatever</p>
      <!--tree-->
      <p>the machine with bing</p>
      <!--house-->
      <p>10% of boo is foo</p>
      </html>"""

      h1=txt.replace( "%","%%")
      h3 = re.sub("<!--(\w+)-->", "%(\\1)s", h1)

      house="somethin g awfull"
      tree="something beautifull"
      print h3 % locals()

      Comment

      Working...