Search & Replace

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • DataSmash

    #1

    Search & Replace

    Hello,
    I need to search and replace 4 words in a text file.
    Below is my attempt at it, but this code appends
    a copy of the text file within itself 4 times.
    Can someone help me out.
    Thanks!

    # Search & Replace
    file = open("text.txt" , "r")
    text = file.read()
    file.close()

    file = open("text.txt" , "w")
    file.write(text .replace("Left_ RefAddr", "FromLeft") )
    file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
    file.write(text .replace("Right _RefAddr", "FromRight" ))
    file.write(text .replace("Right _NonRefAddr", "ToRight"))
    file.close()

  • Marc 'BlackJack' Rintsch

    #2
    Re: Search & Replace

    In <1161898031.481 159.202310@f16g 2000cwb.googleg roups.com>, DataSmash
    wrote:
    I need to search and replace 4 words in a text file.
    Below is my attempt at it, but this code appends
    a copy of the text file within itself 4 times.
    Because you `write()` the whole text four times to the file. Make the 4
    replacements first and rebind `text` to the string with the replacements
    each time, and *then* write the result *once* to the file.
    # Search & Replace
    file = open("text.txt" , "r")
    text = file.read()
    file.close()
    >
    file = open("text.txt" , "w")
    text = text.replace("L eft_RefAddr", "FromLeft")
    text = text.replace("L eft_NonRefAddr" , "ToLeft")
    # ...
    file.write(text )
    file.close()

    Ciao,
    Marc 'BlackJack' Rintsch

    Comment

    • Tim Chase

      #3
      Re: Search &amp; Replace

      Below is my attempt at it, but this code appends
      a copy of the text file within itself 4 times.
      Can someone help me out.
      [snip]
      file = open("text.txt" , "w")
      file.write(text .replace("Left_ RefAddr", "FromLeft") )
      file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
      file.write(text .replace("Right _RefAddr", "FromRight" ))
      file.write(text .replace("Right _NonRefAddr", "ToRight"))
      file.close()

      Well, as you can see, you're writing (write()) the text 4 times.

      Looks like you want something like

      file.write(text .replace("Left_ RefAddr",
      "FromLeft").rep lace("Left_NonR efAddr",
      "ToLeft").repla ce("Right_RefAd dr",
      "FromRight").re place("Right_No nRefAddr", "ToRight"))


      which is about the equiv. of

      text = text.replace(.. .1...)
      text = text.replace(.. .2...)
      text = text.replace(.. .3...)
      text = text.replace(.. .4...)
      file.write(text )

      I would also be remiss if I didn't mention that it's generally
      considered bad form to use the variable-name "file", as it
      shadows the builtin "file".

      There are additional ways if replacements cause problems that
      then themselves get replaced, and this is an undesired behavior.
      However, it looks like your example doesn't have this problem,
      so the matter is moot.

      -tkc


      Comment

      • Bruno Desthuilliers

        #4
        Re: Search &amp; Replace

        DataSmash a écrit :
        Hello,
        I need to search and replace 4 words in a text file.
        Below is my attempt at it, but this code appends
        a copy of the text file within itself 4 times.
        Can someone help me out.
        Thanks!
        >
        # Search & Replace
        file = open("text.txt" , "r")
        NB : avoid using 'file' as an identifier - it shadows the builtin 'file'
        type.
        text = file.read()
        file.close()
        >
        file = open("text.txt" , "w")
        file.write(text .replace("Left_ RefAddr", "FromLeft") )
        file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
        file.write(text .replace("Right _RefAddr", "FromRight" ))
        file.write(text .replace("Right _NonRefAddr", "ToRight"))
        file.close()
        >
        See Mark and Tim's answers for your bug. Another (potential) problem
        with your code is that it may not work too well for big files. It's ok
        if you know that the files content will always be small enough to not
        eat all memory. Else, taking a "line by line" approach is the canonical
        solution :

        def simplesed(src, dest, *replacements):
        for line in src:
        for target, repl in replacements:
        line = line.replace(ta rget, repl)
        dest.write(line )

        replacements = [
        ("Left_RefAddr" , "FromLeft") ,
        ("Left_NonRefAd dr", "ToLeft"),
        ("Right_RefAddr ", "FromRight" ),
        ("Right_NonRefA ddr", "ToRight"),
        ]
        src = open("hugetext. txt", "r")
        dest = open("some-temp-name.txt", "w")
        simplesed(src, dest, *replacements)
        src.close()
        dest.close()
        os.rename("some-temp-name.txt", "hugetext.t xt")

        HTH

        Comment

        • Paddy

          #5
          Re: Search &amp; Replace


          DataSmash wrote:
          Hello,
          I need to search and replace 4 words in a text file.
          Below is my attempt at it, but this code appends
          a copy of the text file within itself 4 times.
          Can someone help me out.
          Thanks!
          >
          # Search & Replace
          file = open("text.txt" , "r")
          text = file.read()
          file.close()
          >
          file = open("text.txt" , "w")
          file.write(text .replace("Left_ RefAddr", "FromLeft") )
          file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
          file.write(text .replace("Right _RefAddr", "FromRight" ))
          file.write(text .replace("Right _NonRefAddr", "ToRight"))
          file.close()
          Check out the Pythons standard fileinput module. It also has options
          for in-place editing.

          (

          )

          - Pad.

          Comment

          • Frederic Rentsch

            #6
            Re: Search &amp; Replace

            DataSmash wrote:
            Hello,
            I need to search and replace 4 words in a text file.
            Below is my attempt at it, but this code appends
            a copy of the text file within itself 4 times.
            Can someone help me out.
            Thanks!
            >
            # Search & Replace
            file = open("text.txt" , "r")
            text = file.read()
            file.close()
            >
            file = open("text.txt" , "w")
            file.write(text .replace("Left_ RefAddr", "FromLeft") )
            file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
            file.write(text .replace("Right _RefAddr", "FromRight" ))
            file.write(text .replace("Right _NonRefAddr", "ToRight"))
            file.close()
            >
            >
            Here's a perfect problem for a stream editor, like
            http://cheeseshop.python.org/pypi/SE/2.2%20beta. This is how it works:
            >>replacement_d efinitions = '''
            Left_RefAddr=Fr omLeft
            Left_NonRefAddr =ToLeft
            Right_RefAddr=F romRight
            Right_NonRefAdd r=ToRight
            '''
            >>import SE
            >>Replacement s = SE.SE (replacement_de finitions)
            >>Replacement s ('text.txt', 'new_text.txt')
            That's all! Or in place:
            >>ALLOW_IN_PLAC E = 3
            >>Replacements. set (file_handling_ flag = ALLOW_IN_PLACE)
            >>Replacement s ('text.txt')
            This should solve your task.

            An SE object takes strings too, which is required for line-by-line
            processing and is very useful for development or verification:
            >>print Replacements (replacement_de finitions) # Use definitions as
            test data

            FromLeft=FromLe ft
            ToLeft=ToLeft
            FromRight=FromR ight
            ToRight=ToRight

            Checks out. All substitutions are made.


            Regards

            Frederic


            Comment

            • DataSmash

              #7
              Re: Search &amp; Replace

              Really appreciate all the all the different answers and learning tips!

              Comment

              Working...