0

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)
Hidd
  • 23
  • 6
  • what have you done to debug it? (e.g. have you printed out `locals()` inside the loop to see how the variables change?) – thebjorn Mar 29 '19 at 18:04
  • ps: step 4 in your description doesn't seem to be in your code...? – thebjorn Mar 29 '19 at 18:06
  • pps: without sample input and expected output, nobody is going to be able to help you. – thebjorn Mar 29 '19 at 18:06
  • No I don't know how to place it ? (Sorry I'm a noob in this) I can try to add some print() in the loop to see what's done by the program. – Hidd Mar 29 '19 at 18:07
  • ps: isn't print(urls) the 4 step ? – Hidd Mar 29 '19 at 18:09
  • PPS: the input are [there](https://stackoverflow.com/q/55191164/11210823) and for the outputs I'm waiting for a list of index integers = (xxx, yyy, xxx, yyy, ...). – Hidd Mar 29 '19 at 18:12

1 Answers1

0

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]
rcriii
  • 687
  • 6
  • 9