Search code examples
pythonloopswhile-loopfindreadfile

Find A->B strings multiples times with a while loop


Hello

I'm on a project who require me to find a string interval multiples times (from display_url to display_resources) in a .txt file. For now I have my code like this but when I'm running it, it never break.

The goal of this code is to :

  1. Search the strings from the le1 / le2 index as starting point.
  2. Update the new found index from the dat / det variables to le1 / le2 [to go to the next string interval in the .txt file (in my test they are four of them)]
  3. Add the le1 & le2 variables to the urls list.
  4. Loop as long as dat & det doesn't returns -1.
  5. Print all of the combination of le1 and le2 obtained in the urls list.

It will help a lot to have your thoughts thanks.


    urls = []
    g = open('tet.txt','r')
    data=''.join(g.readlines())
    count = 0
    le1 = 1
    le2 = 1


    while count >= 0 :
        dat = data.find('display_url', le1)
        det = data.find('display_resources', le2)
        if dat < le1: 
            le1 = le1 +dat
        if det < le2:
            le2 = lez +det
        urls.append(le1)
        urls.append(le2)
        if dat <= 0 :
            count = -1
            break

    print(urls)

Solution

  • If 'display_url' and 'display_resources' are in the string initially, your three if statements never get triggered. You want something like the following, that records det and dat at each step and starts searching again from that point. The while loop goes until both if statements fail.

    le1 = 0
    le2 = 0
    still_looking = True
    while still_looking:
        still_looking = False
        dat = data.find('display_url', le1)
        det = data.find('display_resources', le2)
        if dat >= le1:
            urls.append(dat)
            le1 = dat + 1
            still_looking = True                
        if det >= le2:
            urls.append(det)
            le2 = det + 1
            still_looking = True
    

    with

    data = "somestuffdisplay_url some more stuff display_resources even more stuff display_url lastly more stuff still, can you believe it?"
    

    returns:

    [9, 37, 71]