使用while循环多次查找A-> B字符串 [英] Find A->B strings multiples times with a while loop

查看:79
本文介绍了使用while循环多次查找A-> B字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中,要求我在.txt中多次查找字符串间隔(从 display_url display_resources )文件. 现在,我已经有了这样的代码,但是当我运行它时,它永不中断.

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.

此代码的目标是:

  1. le1 / le2 索引中搜索字符串作为起点.
  2. 将新发现的索引从 dat / det 变量更新为 le1 / le2 [转到.txt文件中的下一个字符串间隔(在我的测试中,它们是其中的四个)]
  3. 添加 le1 & url2 列表中的 le2 变量.
  4. 只要 dat & det 不返回-1.
  5. 打印在 urls 列表中获得的 le1 le2 的所有组合.
  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)

推荐答案

如果最初在字符串中包含'display_url''display_resources',则永远不会触发您的三个if语句.您需要类似以下内容的东西,它在每个步骤中记录det和dat并从该点开始再次搜索. while循环直到两个if语句都失败.

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

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

返回:

[9, 37, 71]

这篇关于使用while循环多次查找A-> B字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆