我正在尝试使用 pyparsing 来解析日志文件。 日志文件条目的结构如下:
information line 1
information line 2
...
information line n
attribute name 1 = attribute value 1
attribute name 2 = attribute value 2
...
attribute name n = attribute value n
我编写了这个语法来解析这个文本 block :
NL = Suppress(LineEnd())
infoline = OneOrMore(Word(alphas + ".-")) + NL
attrib_value_pair = OneOrMore(Word(alphas)) + Suppress("=") + \
OneOrMore(Word(alphanums + ".")) + NL
data = OneOrMore(infoline) + OneOrMore(attrib_value_pair)
parsed_data = data.parseString(trace_block)
我在解析时遇到此错误:
Traceback (most recent call last):
File "filter.py", line 100, in <module>
get_trace_block()
File "filter.py", line 25, in get_trace_block
filter_trace(trace_block)
File "filter.py", line 53, in filter_trace
get_attrib_name_value_pairs(trace_block[2:len(trace_block)])
File "filter.py", line 94, in get_attrib_name_value_pairs
parsed = data.parseString(trace_block)
File "/usr/local/lib/python2.6/dist-packages/pyparsing.py", line 1006, in parseString
raise exc
pyparsing.ParseException: Expected end of line (at char 70), (line:2, col:26)
日志文件中的示例行:
A valid message has been received from a peer
Message type is A
local ip = 10.7.1.10
local port = 3000
remote ip = 10.7.1.20
remote port = 3001
知道哪里出了问题吗? 提前致谢。
最佳答案
你们真的很接近。默认情况下,Pyparsing 的空白跳过包括换行符,因此您的信息行 OneOrMore
将读取单行信息,实际上甚至会读取第一个属性的“本地 ip”。由于您的解析器是面向行的,并且您明确显示了解析器中可以出现换行符的位置,因此您应该告诉 pyparsing 不 将换行符作为可忽略的空格跳过。在定义任何语法元素之前执行此操作:
ParserElement.setDefaultWhitespaceChars(' \t')
现在您将开始从解析器中看到更好的结果。
其他一些提示:
使用 Infoline 和 attrib_value_pair 周围的 Group 为解析的数据添加结构。
当您解析信息行时,OneOrMore 类型表达式将为您提供类似
['A', 'valid', 'message', 'has', 'been', 'received', 'from', 'a', 'peer']
用originalTextFor
包裹信息行,这会将信息行的匹配文本恢复为“有效消息等......”作为单个字符串
祝您的 pyparsing 工作顺利!
关于python - 使用 pyparsing 解析 <attribute value> 对时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14230942/