Searching through a list and replacing items in it...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    Searching through a list and replacing items in it...

    Hi, I need to search through a given file and find certain keys and replace them, in this case it's the symbol "%". I'm not sure how to go about this.

    Code:
    f = open("numbers.txt","r")
    contents = f.read( )
    # I'm not sure why the .split is in here but someone suggested it to me so I 
    # included it. I could .split("%") but then what?
    fields = contents.split(",")
    print fields

    # numbers.txt=
    1234435%3574357 34763736%474526 435151463267%23 943249023403478 234724234782347 234234247824273 423478235%47283 40723840%472347 234023742%72304 372104%472389%4 7204
    47242%742047239 472947247239042 7472482%7429472 4728904273%34%
    21211212122121% 1121212121%6767 6767676767%8787 8787878787%

    I can print the file out like this but I need to replace the 1st, 5th & 13th "%" with "$".

    I tried to do something like this to see if it would just find "%" but it didn't work:
    Code:
    f = open("numbers.txt","r")
    contents = f.read( )
    data = contents.split(",")
    if data.find("%"):
    print "Symbol found"
    ^ gets error message because the .split puts it into a list. I also tried re.search("%").

    Any suggestions?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Thekid
    Hi, I need to search through a given file and find certain keys and replace them, in this case it's the symbol "%". I'm not sure how to go about this.

    Code:
    f = open("numbers.txt","r")
    contents = f.read( )
    # I'm not sure why the .split is in here but someone suggested it to me so I 
    # included it. I could .split("%") but then what?
    fields = contents.split(",")
    print fields

    # numbers.txt=
    1234435%3574357 34763736%474526 435151463267%23 943249023403478 234724234782347 234234247824273 423478235%47283 40723840%472347 234023742%72304 372104%472389%4 7204
    47242%742047239 472947247239042 7472482%7429472 4728904273%34%
    21211212122121% 1121212121%6767 6767676767%8787 8787878787%

    I can print the file out like this but I need to replace the 1st, 5th & 13th "%" with "$".

    I tried to do something like this to see if it would just find "%" but it didn't work:
    Code:
    f = open("numbers.txt","r")
    contents = f.read( )
    data = contents.split(",")
    if data.find("%"):
    print "Symbol found"
    ^ gets error message because the .split puts it into a list. I also tried re.search("%").

    Any suggestions?
    String methods can be used to accomplish your task. [code=Python]def replace_pos(s, old, new, posList):
    idx = -1
    count = 0
    while True:
    '''
    s.find() returns the position of the substring.
    When the end of string is reached and no more
    occurrances of substring are found, s.find()
    returns -1.
    '''
    idx = s.find(old, idx+1)
    count += 1
    if idx == -1:
    return s
    elif count in posList:
    s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])

    fn = r'H:\TEMP\temsy s\numbers1.txt'
    s = open(fn).read()
    oldStr = '%'
    newStr = '$'
    posList = [1,5,13]
    s1 = replace_pos(s, oldStr, newStr, posList)[/code]There is no need to split the string into a list, although there is a way to get the same result.

    Comment

    • Thekid
      New Member
      • Feb 2007
      • 145

      #3
      Great, thank you that works. Now what if I need to change all of them instead of just a few, but don't know how many are in the file? How can I replace them all?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by Thekid
        Great, thank you that works. Now what if I need to change all of them instead of just a few, but don't know how many are in the file? How can I replace them all?
        That's much easier.[code=Python]s2 = s.replace('%', '$')[/code]

        Comment

        • Thekid
          New Member
          • Feb 2007
          • 145

          #5
          Once again thanks, that does the trick. One last question regarding this, what about a loop that will go through and try various combinations? For example, let's say it will replace positions 1,2,3 then try 1,2,4, then try 1,2,5 etc....

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Originally posted by Thekid
            Once again thanks, that does the trick. One last question regarding this, what about a loop that will go through and try various combinations? For example, let's say it will replace positions 1,2,3 then try 1,2,4, then try 1,2,5 etc....
            The function replace_pos() should work for that.

            Comment

            • Thekid
              New Member
              • Feb 2007
              • 145

              #7
              Originally posted by bvdet
              The function replace_pos() should work for that.
              I've played around with the replace_pos() but still can't seem to get it to work as a loop. This is it so far:

              Code:
              def replace_pos(s, old, new, posList):
                  idx = -1
                  count = 0
                  while True:
                      '''
                      s.find() returns the position of the substring.
                      When the end of string is reached and no more
                      occurrances of substring are found, s.find()
                      returns -1.
                      '''
                      idx = s.find(old, idx+1)
                      count += 1
                      if idx == -1:
                          return s
                      elif count in posList:
                          s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])   
              
              # I changed this part slightly
              fn = open("numbers.txt","r")
              s = (fn).read()
              oldStr = "#"
              newStr = "@"
              posList = [1,2,3]
              s1 = s.replace("%","#")
              s2 = replace_pos(s1, oldStr, newStr, posList)
              print s2
              This is taking the 'numbers.txt' and first replacing all of the '%' symbols with '#'. It then replaces the 1,2,3 '#' symbols with '@'. What I want to do is first change all of the symbols but then have a loop replace the 1,2,3 symbols. If they are the correct combinations then it's done, if not I need the code to replace the 1,2,4 positions, then 1,2,5 and so on until all combinations are checked. Also, I can 'write' to the file by adding the code below but it doesn't fit in to the loop because it saves the changes and that throws off the next run through of the code:


              Code:
              solution = s2
              f 2= open("numbers.txt","w")
              f2.write(solution)
              f2.close
              print solution

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Originally posted by Thekid
                I've played around with the replace_pos() but still can't seem to get it to work as a loop. This is it so far:

                Code:
                def replace_pos(s, old, new, posList):
                    idx = -1
                    count = 0
                    while True:
                        '''
                        s.find() returns the position of the substring.
                        When the end of string is reached and no more
                        occurrances of substring are found, s.find()
                        returns -1.
                        '''
                        idx = s.find(old, idx+1)
                        count += 1
                        if idx == -1:
                            return s
                        elif count in posList:
                            s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])   
                
                # I changed this part slightly
                fn = open("numbers.txt","r")
                s = (fn).read()
                oldStr = "#"
                newStr = "@"
                posList = [1,2,3]
                s1 = s.replace("%","#")
                s2 = replace_pos(s1, oldStr, newStr, posList)
                print s2
                This is taking the 'numbers.txt' and first replacing all of the '%' symbols with '#'. It then replaces the 1,2,3 '#' symbols with '@'. What I want to do is first change all of the symbols but then have a loop replace the 1,2,3 symbols. If they are the correct combinations then it's done, if not I need the code to replace the 1,2,4 positions, then 1,2,5 and so on until all combinations are checked. Also, I can 'write' to the file by adding the code below but it doesn't fit in to the loop because it saves the changes and that throws off the next run through of the code:


                Code:
                solution = s2
                f 2= open("numbers.txt","w")
                f2.write(solution)
                f2.close
                print solution
                You need to have some way to determine the replacement position lists. What are "all combinations"? After you create the all combinations list, then you can iterate on that list.[code=Python]comb_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,4,5], [2,3,4], [3,4,5]]

                for clist in comb_list:
                s1 = replace_pos(s, oldStr, newStr, clist)[/code]

                Comment

                Working...