如何通过pyparsing得到包含多个关键词的整行?

2024-10-06 19:20:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pyparsing来解析日志文件。我想得到包含关键字的整行:

  • Input/Output error
  • Disk full
  • Quota Exceeded

我的代码如下:

import pyparsing as pp
line = pp.Combine(pp.Regex(".*") + pp.CaselessLiteral("Input/Output error") ^ \
       pp.CaselessLiteral("Disk full") ^ pp.CaselessLiteral("Quota Exceed") + \ 
       pp.Regex(".*"))

在匹配结果中,它只包含诸如"Disk full"之类的关键字。这并不是全部

有人知道如何在结果中得到完整的结果吗


Tags: 文件代码importinputoutputerror关键字pyparsing
1条回答
网友
1楼 · 发布于 2024-10-06 19:20:33

尝试将此解析操作附加到line

def return_containing_line(s, l, t):
    # use pyparsing line builtin to extract the current line text
    # at location 'l' in input string 's'
    return pp.line(l, s)
line.addParseAction(return_containing_line)

这个解析器真的有效吗?我认为前导的Regex会占用整行,因为它不会对下面的文字表达式进行任何展望。为什么不去掉Regex术语而直接使用searchString?或者如果您使用scanString,您将为每个匹配得到一个(tokens, startloc, endloc)元组,您可以使用startloc和输入字符串调用pp.line,甚至不需要解析操作

相关问题 更多 >