繁体   English   中英

在 if 语句之后循环并继续 for 循环

[英]looping after if statement and continue the for loop

我正在尝试遍历 a.txt 文件,当我找到一个关键字时,我想遍历接下来的 5 行,但我无法让我的循环继续。

这是文本:

11/9/2022 12:37 a. m. - J E. Meta: *Plantilla de contacto*
Respuesta #10002
Nombre: Jesus Meta 
Numero Telefonico: 656-199-4322
Monto de Credito: 1200
Numero de Cliente: 127388
Ya tiene su ultimo estacional pagado?: Si

当我找到关键字“Respuesta”时,我希望循环在接下来的 5 行中继续:所以我需要得到:

Nombre:
Numero:
Monto:
Etc:

这是我的代码,我能够找到关键字,但是在找到关键字之后。 我的循环停止了,我无法让它继续,所以我得到了接下来需要得到的 5 行。

import os 


path = os.getcwd() + "/prestamos.txt"

with open(path) as file:
    data = file.readlines()
    for row in data:
        if "Respuesta" in row:
            print(row)


谢谢!

对我有用的代码

我最终用while坚持了一个不同的循环:

这是对我有用的代码,以防它帮助其他人:

import os 
import pandas as pd

path = os.getcwd() + "/prestamos.txt"

ls = {}
with open(path) as file:
    data = file.readlines()
    n = 0
    while n <= len(data)-1:
        if "Respuesta" in data[n]:
            r = range(n,n+6)
            for row in r:
                #print(row,data[row])
                col,actual_data = data[row].strip().split(":")
                #print(col,actual_data)
                if col not in ls:
                    ls.update({col:[actual_data]})
                elif col in ls:
                    ls[col].append(actual_data)

        n += 1



df = pd.DataFrame(ls)
print(df.head())

谢谢你!

以您的方式:

import os 


path = os.getcwd() + "/prestamos.txt"

with open(path) as file:
    data = file.readlines()
    for row in data:
        if "Respuesta" in row:
            print(row)
            # printing the next 5 lines as well:
            for _ in range(5):
                print(next(data))

或者进行一些修改和更多的灵活性:

import os 

path = os.getcwd() + "/prestamos.txt"

with open(path) as file:
    # since `file` is a text file, you can loop directly over it
    for line in file:
        if 'Respuesta' in line:
            next_5 = [next(file) for _ in range]
            # now, next_5 is a list of those 5 lines, you can work with it
        # the code would continue and find the next block, if you file has multiple    

另一种解决方案:

import os 


path = os.getcwd() + "/prestamos.txt"

with open(path) as file:
    count = 0
    found = false
    for row in data:
        if 'Respuesta' in data:
            found = true
            count = 0
        if found and count < 5:
            print(row)
            count += 1

在这里,我使用found来跟踪我何时找到"Respuesta" 然后我在找到它后使用count来跟踪行数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM