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 :
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)
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]