You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在找到关键词后继续循环读取TXT文件的后续5行?

问题:遍历TXT文件定位关键词后读取后续5行数据

需要遍历一个.txt文件,当找到关键词“Respuesta”时,读取后续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

最初的代码(仅能定位关键词行)

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)

最终实现代码(获取后续行并整理为DataFrame)

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]:
            # 取当前行及后续5行,共6行数据
            r = range(n, n+6)
            for row_idx in r:
                line = data[row_idx].strip()
                col, actual_data = line.split(":")
                # 整理为字典,用于生成DataFrame
                if col not in ls:
                    ls[col] = [actual_data]
                else:
                    ls[col].append(actual_data)
        n += 1

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

实现思路

最初的for循环仅遍历每行判断关键词,无法直接关联后续行的索引。改用while循环通过索引n控制遍历,当找到关键词所在行时,通过range(n, n+6)获取当前行及后续5行的索引范围,遍历这些行拆分键值对,将数据整理为字典后转换为Pandas DataFrame,完成数据提取与结构化。

内容的提问来源于stack exchange,提问作者mcbdx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:55:25