【问题标题】:Find A->B strings multiples times with a while loop使用 while 循环多次查找 A->B 字符串
【发布时间】:2019-03-29 17:56:53
【问题描述】:

你好

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

这段代码的目标是:

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

感谢您的想法对您有很大帮助。


    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)

【问题讨论】:

  • 你做了什么来调试它? (例如,您是否在循环内打印出locals() 以查看变量如何变化?)
  • ps:您描述中的第 4 步似乎不在您的代码中...?
  • pps:没有样本输入和预期输出,没有人能帮助你。
  • 不,我不知道怎么放? (对不起,我是个菜鸟)我可以尝试在循环中添加一些 print() 来看看程序做了什么。
  • ps:print(urls) 不是 4 步吗?

标签: python loops while-loop find readfile


【解决方案1】:

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

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]

【讨论】:

  • 非常感谢你是救命稻草。
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 2019-04-26
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 2018-12-11
  • 1970-01-01
相关资源
最近更新 更多