如何循环遍历循环中的剩余元素

1、问题背景

给定一段文本,文本中包含多条错误信息,每条错误信息包含行号、错误路径和错误信息。需要从文本中提取出这些错误信息,并以特定的格式输出。

python 复制代码
line, Error = 12, This is the Error
line, Error = 34, Another Error
line, Error = 90, Error Three

使用以下代码可以完成提取错误信息的任务:

python 复制代码
theText = 'ERROR: ...'
ERROR_RE = re.compile(r'^ERROR: <(?P<path>.*):(?P<line>[0-9]+)> (?P<error>.*)$')
mainName = '\Main.ext'
# 遍历每一行
for fullline in theText.splitlines():
    match = self.ERROR_RE.match(fullline)
    if match:
        path, line, error = match.group('path'), match.group('line'), match.group('error')
        if path.endswith(mainName):
            callSomething(line, error)
        # 否则检查下一行是否有'Call Trace:'
        # 检查下一行是否有mainName并获取行号
        # callSomething(linenumber, error)

问题是,在检查完一行后,如何循环遍历剩余的行以提取下一条错误信息?

2、解决方案

直接循环遍历剩余元素的方法是将循环的第一行改为:

python 复制代码
lines = theText.splitlines()
for (linenum, fullline) in enumerate(lines):
```pyhton

然后,在匹配之后,可以通过查看 `lines[j]` 来获取剩余的行,其中 `j` 从 `linenum+1` 开始,一直运行到下一个匹配。

但是,解决这个问题的更巧妙的方法是首先将文本分割成块。有许多方法可以做到这一点,但是作为前 perl 用户,我的冲动是使用正则表达式。

```pyhton
# 将文本分割成以 /^ERROR/ 开头并一直持续到下一个 /^ERROR/ 或字符串结尾的块。
#
# (?m)      - 让 '^' 和 '$' 匹配每行的开头/结尾
# (?s)      - 让 '.' 匹配换行符
# ^ERROR    - 触发匹配的开始
# .*?       - 以非贪婪的方式获取字符,在以下表达式匹配时停止
# (?=^ERROR|$(?!\n)) - 匹配直到下一个 /^ERROR/ 或字符串结尾
# $(?!\n)   - 匹配字符串结尾。通常 '$' 就足够了,但由于我们用 '(?m)' 启用了多行模式,所以我们必须使用 '(?!\n)$' 来防止它匹配行尾。
blocks = re.findall('(?ms)^ERROR.*?(?=^ERROR|$(?!\n))', theText)

现在,我们可以遍历这些块,并从每个块中提取错误信息:

python 复制代码
for block in blocks:
    match = ERROR_RE.match(block)
    if match:
        line, error = match.group('line'), match.group('error')
        callSomething(line, error)

这将提取出文本中的所有错误信息,并以指定格式输出。

代码例子:

python 复制代码
import re

theText = '''ERROR: <C:\Includes\Library1.inc:123> This is the Error
Call Trace:
    <C:\Includes\Library2.inc:456>
    <C:\Includes\Library2.inc:789>
    <C:\Code\Main.ext:12> 
    <Line:1> 
ERROR: <C:\Includes\Library2.inc:2282> Another Error
Call Trace:
    <C:\Code\Main.ext:34>
    <C:\Code\Main.ext:56>
    <C:\Code\Main.ext:78>
    <Line:1> 
ERROR: <C:\Code\Main.ext:90> Error Three'''

ERROR_RE = re.compile(r'^ERROR: <(?P<path>.*):(?P<line>[0-9]+)> (?P<error>.*)$')
mainName = '\Main.ext'

# 将文本分割成块
blocks = re.findall('(?ms)^ERROR.*?(?=^ERROR|$(?!\n))', theText)

# 从每个块中提取错误信息
for block in blocks:
    match = ERROR_RE.match(block)
    if match:
        line, error = match.group('line'), match.group('error')
        print(f'line, Error = {line}, {error}')

输出结果:

pythion 复制代码
line, Error = 123, This is the Error
line, Error = 2282, Another Error
line, Error = 90, Error Three
相关推荐
starzy19901 天前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y1 天前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静1 天前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL1231 天前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_091 天前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
吴可可1231 天前
WScript Shell操作注册表详解
开发语言
纪念 2291 天前
C++ 算法基础 (差分)
开发语言·c++·算法
databook1 天前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈1 天前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao1 天前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib